其他分享
首页 > 其他分享> > 前端文件上传+expressJs后端文件写入

前端文件上传+expressJs后端文件写入

作者:互联网

方式1:前端FormData + 后端multiparty

前端

_file是通过<input type='file' />获得的文件
upload_btn_upload.addEventListener('click', function () {
  if (!_file) {
    console.error('has not select file~~');
    return
  }
  let formData = new FormData()
  //前端传入file,filename
  formData.append('file', _file)
  formData.append('filename', _file.name)
  axios.post('/', formData).then(data => {
    console.log(data);
  }).catch(reson => {
    throw reson
  })
})

后端

npm i multiparty

const multiparty = require('multiparty')

const formidable_upload = (req) => {
  return new Promise((resolve, reject) => {
    //multyparty的配置
    const config = {
      uploadDir: path.join(__dirname, '../img') //文件写入的目录
    }
    new multiparty.Form(config).parse(req, (err, fields, files) => {
      if (err) {
        reject(err)
        return
      }
      resolve({ fields, files })
    })
  })
}

index.post('/', async (req, res, next) => {
  try {
    let { fields, files } = await formidable_upload(req)
    let file = files.file || {}
    res.send({ code: 0, codeText: 'upload_success' })
  } catch (err) {
    res.send({ code: 1, codeText: err })
  }
});

标签:文件,err,multiparty,formData,req,写入,upload,expressJs,file
来源: https://www.cnblogs.com/Lilc20201212/p/15869703.html