简体   繁体   中英

Corrupt files/images when uploaded to nodejs

I already googled all the internet and I didn't find my issue yet. I'm using multipart to upload to nodejs, but all my files are coming corrupted, I used many solutions of parsing and I can do it with formidable, but I want to learn how to parse by my own. The binary code of the output file is exactly the same of the original[size and binary(I used hexdump -C int terminal to check)].

Here's a sample of the code:

 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"); }); }); } 

You're sending a multipart request. This means it's not just the raw contents of the single file you're uploading, but a special format that allows for multiple parts where each part is a separate form field (in your case there is only 1 part -- the file form field). You should look into using a module that can parse multipart/form-data requests for you such as busboy , multiparty , or formidable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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