在节点js中上传图片

编程入门 行业动态 更新时间:2024-10-23 05:01:05
本文介绍了在节点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中上传图片

本文发布于:2023-11-26 17:02:12,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   上传图片   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!