1. 程式人生 > >nodejs+multiparty 文件上傳

nodejs+multiparty 文件上傳

nco char app .com multi har style dev header

通過表單提交上傳文件:

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

nodejs+multiparty 文件上傳