admin管理员组

文章数量:1241106

I was wondering if I can upload string as file using form data. I believe there should be some File object, that can have value, filename and maybe also mime-type set.
Pseudo code:

var file = new File();
file.name = "file.txt";
file.mimeType = "text/plain";
file.value = "blah blah\nsecond line";
var data = new FormData();
data.append(file);

I was wondering if I can upload string as file using form data. I believe there should be some File object, that can have value, filename and maybe also mime-type set.
Pseudo code:

var file = new File();
file.name = "file.txt";
file.mimeType = "text/plain";
file.value = "blah blah\nsecond line";
var data = new FormData();
data.append(file);
Share Improve this question asked Feb 15, 2013 at 13:31 Tomáš ZatoTomáš Zato 53.2k63 gold badges308 silver badges822 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 18

works fine for me

const blob = new Blob(['blah blah\nsecond line'], {type : 'text/plain'})
formData.append('file', blob, 'file.txt')

For anyone arriving here and using zag2art's answer but running into the error "Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream", you need to install the "form-data" package and use that to get past this error.

npm i --save form-data

Then you need to wrap the filename in an options object, and for me I had to switch to Buffer instead of Blob as although theoretically supported causes a new error.

import FormData = require('form-data');

...

const blob = Buffer.from('here is the text you want to upload', 'utf8');
const formData = new FormData();
formData.append('file', blob, {filename: 'file.txt'});

There is indeed an object called File(on modern browsers), but you cannot create a new instance of it, out of security issues. Therefore, what you seek is not possible.

本文标签: javascriptAppend string as file upload using FormDataStack Overflow