12

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);

3 Answers 3

18

works fine for me

const blob = new Blob(['blah blah\nsecond line'], {type : 'text/plain'})
formData.append('file', blob, 'file.txt')
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much for posting this. That type object as the second argument of Blob was what I've been looking for!!
1

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'});

Comments

-8

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.

3 Comments

What OP is trying to do is possible. See zag2art's answer below.
i don't know whether you tried to reproduce the scenario or test the code but this Ans should not be marked as answer, as the solution from @zag2art's is clearly working, which shows modern browsers does allow what was asked in the question.
@ipetrik This answer was posted in 2013, back then it was correct afaik. I changed accepted answer now that we have file related APIs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.