I'm a newbie in Node.js and trying to upload an image from my html. I created the button which can upload image to my web app by using below html code.
<li><a onclick="getFile()" style="cursor:pointer; color:#000000;">Choose File</a></li>
<li><a onclick="uploadFile();" style="cursor: pointer; color:#000000;">Upload</a></li>
<li><a onclick="save2()" id="imageSave" style="cursor:pointer; color:#000000;">Save</a></li>
<li><a href="/location" style="color:#000000">Back to view</a></li>
<form action="/upload", method="post", enctype="multipart/form-data">
<div style='height:0px; width:0px; overflow:hidden;'><input type="file" name="upFile" id="upFile" onchange="getCmaFileView(this, 'name')" target="dropzone_1"/></div>
<div style='height:0px; width:0px; overflow:hidden;'><input type="submit" name="Upload" id="Upload" /></div>
</form>
After clicking upload li it uploads an image from node.js by using multiparty package like code below.
app.post('/upload', function(req, res, next) {
var form = new multiparty.Form();
// get field name & value
form.on('field',function(name,value){
console.log('normal field / name = '+name+' , value = '+value);
});
// file upload handling
form.on('part',function(part){
var filename;
var size;
if (part.filename) {
filename = part.filename;
size = part.byteCount;
}else{
part.resume();
}
console.log("Write Streaming file :"+global_username);
var writeStream = fs.createWriteStream('/opt/work/files/'+global_username);
writeStream.filename = filename;
part.pipe(writeStream);
part.on('data',function(chunk){
console.log(global_username+'.png'+' read '+chunk.length + 'bytes');
});
part.on('end',function(){
console.log(global_username+'.png'+' Part read complete');
writeStream.end();
});
});
// all uploads are completed
form.on('close',function(){
res.status(200);
});
// track progress
form.on('progress',function(byteRead,byteExpected){
console.log(' Reading total '+byteRead+'/'+byteExpected);
});
form.on('error',function(){
console.log('error');
});
form.parse(req);
});
It saves an image and uploads well, but it shows me an ERROR after waiting a while with ERR_EMPTY_RESPONSE message.
I think it is because of response. it means that after header goes post, should give it back response but it doesn't.
And actually, I wrote code that it gives response back in above code of Node.js
form.on('close',function(){
res.status(200);
});
However, it still gives same error... I don't know why.
Does anybody have an idea? or am I wrong?