问题
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