通过表单提交上传文件:
html代码
<form action="/uploadFile" method="post" enctype="multipart/form-data"> <input type="file" class="files" id="files" name="files"> <input type="submit" class="uploadFile" value="文件上传"> </form>
windows下安装multiparty
npm install multiparty
multiparty使用:multiparty文档 https://www.npmjs.com/package/multiparty
multiparty代码
var multiparty = require(‘multiparty‘); app.post(‘/uploadFile‘,function(req.res){ var form = new multiparty.Form(); // res.setHeader(‘text/plain‘); var msg = {info:‘‘,img:‘‘}; console.log(__dirname); form.encoding = ‘utf-8‘; form.uploadDir = __dirname+"/uploads"; //设置单文件大小限制 form.maxFilesSize = 2 * 1024 * 1024; //form.maxFields = 1000; 设置所以文件的大小总和 form.parse(req, function(err, fields, files) { if(err){ console.log(‘错误‘); msg.info = ‘上传失败‘; res.send(msg); return ; } console.log(files.files[0].originalFilename); msg.img=path.join(__dirname,‘/uploads/‘+files.files[0].originalFilename); console.log(msg.img); msg.info = ‘上传成功‘ msg.len = files.length; res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"}); res.send(msg); }); });
参考链接:
https://www.npmjs.com/package/multiparty
https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/form
时间: 2024-10-05 03:14:52