avatar
fireworks99
keep hungry keep foolish

Upload files to Server

Description

通过form表单提交文件到服务器

HTML

<form action="http://localhost:3000/uploadImg"
              method="post"
              enctype="multipart/form-data"
              class="ava_form">
    <label class="ava_change_text">头像(可更换)</label>

    <input name="imgFile" type="file" accept="image/gif, image/jpeg" class="ava_change_file" />
    <input name="upload" type="submit" value="提交"  class="ava_change_submit" />
</form>

NodeJS

npm i multiparty
const multiparty = require('multiparty')
router.post('/uploadImg', function (req, res) {
  const form = new multiparty.Form({
    uploadDir: './public/img_upload'
  })

  form.parse(req, function (err, fields, files) {
    if(err) throw err;
    else res.send(JSON.stringify(files.imgFile[0]));
    // 通过form.parse生成服务器文件,这里生成的文件名字不是原来的名字,而是编码后的名字
  })
})
Site by Baole Zhao | Powered by Hexo | theme PreciousJoy