npm Formidable Upload, use with JS FormData on client

穿精又带淫゛_ 提交于 2021-02-10 20:21:47

问题


I wanna send a file to the server with FormData by drag and drop, and save it to disk with Formidable in node.

I used this code to send the file: https://github.com/felixge/node-formidable#example

and it works, my server saves the data, but I can't send it via js FormData. I wrote this code, but it doesn't parse the received data as files, and shows them like fields. The code is describe this better:

// Client code
//inside drop event so i have files:

files = event.dataTransfer.files;
file = files[0];

reader = new FileReader();

reader.readAsArrayBuffer(file);

reader.onload = function(evt) {
    var data, fd;
    data = evt.target.result; // it's real binary data on log
    fd = new FormData;
    fd.append("foo", "bar");
    fd.append("upload", data);
    uploadImage(fd);
}

uploadImage = function(data) {
    xmlHttp.overrideMimeType("multipart/form-data");
    xmlHttp.open('post', '/upload');
    xmlHttp.send(data);
}

It works and sends the data to the server, but formidable's parse method logs like this:

fields: {foo: 'bar', upload=''}
files: {}

回答1:


After lot's of changes, finally found a way! This is my reader Code:

reader.readAsArrayBuffer(file);

I changed type of file, from buffer to Blob, and it works:

arrayBufferToBlob: function(buffer, opt_contentType) {
    var uInt8Array;
    uInt8Array = new Uint8Array(buffer);
    return new Blob([uInt8Array], (opt_contentType ? {
        type: opt_contentType
    } : {}));
}

changes of client code:

//Changes of Client:
fd = new FormData;
data = arrayBufferToBlob(data);
fd.append("upload", data, "FileName");

And log of nodeJS server looks like:

fields: {foo: 'bar'}
files: {'fileName'}

I think Chrome (not tried on other browsers) HTML File tag uses Blob for HTML Forms to post... If you had idea, tell here!



来源:https://stackoverflow.com/questions/17427102/npm-formidable-upload-use-with-js-formdata-on-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!