简体   繁体   English

Node.js上传块并将其保存到文件

[英]Node.js upload chunk and save it to the file

It was a long day with no success, trying to upload a file to the server and save it. 漫长的一天没有成功,试图将文件上传到服务器并保存。 For example, i want to upload an image file to a server, I managed to do it with pulpload and HTTP module. 例如,我想将图像文件上传到服务器,我设法用纸浆负载和HTTP模块来完成此操作。 I do receive the chunk and I can save it to the file, but the file is not opening. 我确实收到了块,可以将其保存到文件中,但是文件没有打开。 Here is my code: 这是我的代码:

**server side:**
    var http = require('http');
    http.createServer(function (req, res) {

      req.on('data', function(chunk) {

           fs.appendFileSync(__dirname +'/file.jpg' , chunk, function (err) {

           })
       })

    }).listen(8081);

After I receive all chunk, the file contains some data that I am not sure this data belongs to a jpg file: 收到所有块后,该文件包含一些数据,我不确定该数据是否属于jpg文件:

------WebKitFormBoundaryP6RBw3nrYvsnhYhw
Content-Disposition: form-data; name="name"

3fd639c096a4196a8d9bfbf2f568a87fc-f0xd-w1020_h770_q80.jpg
------WebKitFormBoundaryP6RBw3nrYvsnhYhw
Content-Disposition: form-data; name="chunk"

0
------WebKitFormBoundaryP6RBw3nrYvsnhYhw
Content-Disposition: form-data; name="chunks"

1
------WebKitFormBoundaryP6RBw3nrYvsnhYhw
Content-Disposition: form-data; name="fileupload"; filename="blob"
Content-Type: application/octet-stream

ÿØÿà JFIF

When all chunk have been saved, I cant open the file, I tried many tutorials and modules but had no success. 保存所有块后,我无法打开文件,我尝试了许多教程和模块,但未成功。 My question, is it possible to do it? 我的问题,有可能做到吗? I did manage to do it with php, java and even with coldfusion it was pice of cake but with node.js it's a nightmare. 我确实设法用php,java做到了这一点,即使使用ColdFusion,这也是小菜一碟,但使用node.js却是一场噩梦。 I did google all over, but most tutorials are outdated and do not work. 我遍历了谷歌,但是大多数教程已经过时了,无法正常工作。 I don't want to spend my time on this anymore, I hope I will get some help here or right directions to solve it. 我不想再花时间在此上,我希望我能在这里得到一些帮助或正确的方向来解决它。 thanks in advance 提前致谢

In multipart/form-data requests, form fields are separated using boundaries. 在多部分/表单数据请求中,表单字段使用边界分隔。 The body needs to be parsed to get the fields or data. 需要解析正文以获取字段或数据。 There are numerous modules available for this, 'multiparty' being one of them. 有很多可用的模块,“多方”就是其中之一。 Perhaps, this should get you going: 也许,这应该可以帮助您:

var http = require('http');
var fs = require('fs');
var multiparty = require('multiparty');
http.createServer(function (req, res) {
if (req.method === 'POST') {
    var form = new multiparty.Form();
    form.parse(req, function (err, fields, files) {
        /* assuming <input type="file" name="profile" /> is used in upload form */
        var profileImageFileArray = files.profile;
        if (profileImageFileArray && profileImageFileArray.length > 0) {
            var profileImageFile = profileImageFileArray[0];
            var tempFilePath = profileImageFile.path;
            var newFilePath = __dirname + '/uploads/' + profileImageFile.originalFilename;
            fs.readFile(tempFilePath, (err, data) => {
                fs.writeFile(newFilePath, data, (err) => {
                    /* handle response according to success or error */
                });
            });
        }
    });
}
else {
    var html = fs.readFileSync('index.html');
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(html);
}}).listen(9090);

Non binary fields can be extracted from 'fields' argument passed, similar to the files. 可以从传递的'fields'参数中提取非二进制字段,类似于文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM