上传到nodejs时损坏的文件/图像

Corrupt files/images when uploaded to nodejs

本文关键字:文件 图像 损坏 nodejs      更新时间:2023-09-26

我已经在谷歌上搜索了所有的互联网,但我还没有找到我的问题。我使用multipart上传到nodejs,但我所有的文件都被破坏了,我使用了许多解析解决方案,我可以用强大的功能来完成,但我想学习如何自己解析。输出文件的二进制代码与原始的[size和binary(我使用了hexdump-C int终端进行检查)]完全相同。

以下是代码示例:

var http = require("http");
var fs = require("fs");
http.createServer(function(req, res){
    if(!((req.url === "/upload") && (req.method === "POST"))){
        home(res);
    }else{
        upload(req, res);
    }
}).listen(8888);
function home(res){
    res.end("<html><body><form action='/upload' method='post' enctype='multipart/form-data''><input name='file' type='file'/><input type='submit'></form></body></html>");
}
function upload(req, res){
   
    var data = "";
    req.setEncoding("binary");
    req.addListener("data", function(chunk){
        data = chunk.split("'r'n")[4];/*This was my last chance, but it also failed*/
    });
    req.addListener("end", function(){
        res.end();
        console.log(data);
        fs.writeFile("icone.ico", data, "binary", function(err){/*I also used fs.createWriteStream*/
            console.log("done");
        });
    });
}

您正在发送一个多部分请求。这意味着它不仅仅是你上传的单个文件的原始内容,而是一种特殊的格式,允许多个部分,每个部分都是一个单独的表单字段(在你的情况下只有一个部分——文件表单字段)。您应该考虑使用一个可以为您解析multipart/form-data请求的模块,如busboymultipartyformidable