Reputation: 313
I am trying to upload an image to node.js, which works just fine with this following code:
Client side:
$("#portrait-upload").change(function(e) {
var data = e.target.files[0];
$.ajax({
url: "/upload",
type: "POST",
data: data,
cache: false,
processData: false,
contentType: "multipart/form-data",
success: function(response) {
console.log(response);
}
});
});
Server side:
if(req.url == "/upload"){
var image = fs.createWriteStream("temp.jpg");
req.on("data", function(chunk) {
image.write(chunk);
res.write("Data received.\n");
});
req.on("end", function() {
image.end();
res.end("Data reception ended.");
});
}
Additionally though, I want to read the file's name on the server side. Apparently, I cannot read it out of the request object (at least I did not find a proper method). So I thought POSTing a JSON object with both the file's name and the file itself - something like this:
{ filename : data.name, file: data }
But this does apparently not work - is it even possible to put image-data into a JSON object like that and read it out on the server?
What would be a better method of transmitting both the file's name and the image file itself to node?
Thanks
Upvotes: 0
Views: 824
Reputation: 33399
You can send the file name as a GET parameter instead of POST.
Upvotes: 1