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
3 Answers
Reset to default 18works 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.