avatar
fireworks99
keep hungry keep foolish

formidable upload text and files

Description

npm第三方库multiparty可处理文件上传的问题,我猜应该也能处理文件与文本同时上传的问题,但我先找到了formidable这个库来解决这一问题。表单属性enctype="multipart/form-data"限制了不对字符编码,但普通文本不编码无法传输。另外补充一句<input>标签不带name无法获取value。

npm第三方库formidable

formidable库用于处理上传的表单(包含文本和文件,主要是处理文件)

const formidable = require('formidable') router.post('/uploadImg', function (req, res) { const form = new formidable.IncomingForm(); form.encoding = "utf-8"; form.uploadDir = './public/img_upload'; form.parse(req, function(err, field, files) { // console.log(field); const oldPath = files.imgFile.path; const newPath = oldPath + files.imgFile.name; fs.rename(oldPath, newPath, (err)=>{ if(err) throw err; }) // res.json(files); res.redirect('http://localhost:8080/profile?id=' + field.username) }) })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

当服务端全部接收完客户端用post方式提交的文件或图片之后,触发执行回调函数function(err, field, files)

field(object) : 表单域数据

files(object) : 上传的文件、图片等文件域

上传文件的目录需要事先建好(据说)

文件上传后无后缀名,为此重命名一下

Site by Baole Zhao | Powered by Hexo | theme PreciousJoy