npm 强大的上传,在客户端与 JS FormData 一起使用 [英] npm Formidable Upload, use with JS FormData on client

查看:88
本文介绍了npm 强大的上传,在客户端与 JS FormData 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过拖放使用 FormData 将文件发送到服务器,然后使用 Formidable 在节点中.

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

我使用此代码发送文件:https://github.com/felixge/node-强大#example

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

它可以工作,我的服务器保存了数据,但我无法通过 js FormData 发送它.我写了这段代码,但它不会将接收到的数据解析为文件,而是像字段一样显示它们.代码更好地描述了这一点:

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: {}

推荐答案

经过多次修改,终于找到方法了!这是我的读者代码:

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

reader.readAsArrayBuffer(file);

我更改了文件类型,从 bufferBlob,它可以工作:

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:
fd = new FormData;
data = arrayBufferToBlob(data);
fd.append("upload", data, "FileName");

nodeJS 服务器的日志如下所示:

And log of nodeJS server looks like:

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

我认为 Chrome(未在其他浏览器上尝试过)HTML File 标签使用 Blob for HTML Forms 来发布...如果您有想法,请在此处告诉!

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

这篇关于npm 强大的上传,在客户端与 JS FormData 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆