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
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.
本文标签: javascriptAppend string as file upload using FormDataStack Overflow
版权声明:本文标题:javascript - Append string as file upload using FormData - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740001952a2219627.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论