本文介绍了在节点js中上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了这样的表单,如何在后端节点中处理这个js
< form method =postenctype =multipart / form-dataaction =/ file-upload> < input type =textname =username> < input type =passwordname =password> < input type =filename =thumbnail> < input type =submit>解决方案
使用这种方法上传
app.post('/ upload',function(req,res){ //获取文件的临时位置 var tmp_path = req.files.thumbnail.path; //设置文件实际存在的位置 - 在这种情况下,位于images 目录 target_path ='/ tmp /'+ req.files.thumbnail.name; //将文件从临时位置移动到目标位置 fs.rename(tmp_path,target_path ,函数(err){ if(err)throw err; //删除临时文件,这样显式设置的临时上传目录不会被不需要的文件填充 fs.unlink (tmp_path,function(){ if(err)throw err; }); }); });在此方法中显示路径时, < pre $ fs.readFile(target_path,binary,function(error,file){ if(error){ res.writeHead(500,{Content (); res.end(); } else { res.writeHead(200,{Content-Type:image / png}); res.write(file,binary); } });
请参阅以获取更多详细信息
Im new to node js now i want to do image upload.so i downloaded express framework to handle the upload.Please help me how to handle that upload in server side.
i created form like this how to handle this in back end node js
<form method="post" enctype="multipart/form-data" action="/file-upload"> <input type="text" name="username"> <input type="password" name="password"> <input type="file" name="thumbnail"> <input type="submit">解决方案
Use this method for uploading
app.post('/upload', function(req, res) { // get the temporary location of the file var tmp_path = req.files.thumbnail.path; // set where the file should actually exists - in this case it is in the "images" directory target_path = '/tmp/' + req.files.thumbnail.name; // move the file from the temporary location to the intended location fs.rename(tmp_path, target_path, function(err) { if (err) throw err; // delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files fs.unlink(tmp_path, function() { if (err) throw err; }); }); });While retriving show that path in this method
fs.readFile(target_path, "binary", function(error, file) { if(error) { res.writeHead(500, {"Content-Type": "text/plain"}); res.write(error + "\n"); res.end(); } else { res.writeHead(200, {"Content-Type": "image/png"}); res.write(file, "binary"); } });Refer nodejs expressjs upload images and display them for more details
更多推荐
在节点js中上传图片
发布评论