Reputation:
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. 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:
------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. 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
Upvotes: 0
Views: 2982
Reputation: 23
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.
Upvotes: 1