Vue+axios+Node+express实现文件上传(用户头像上传)

Vue 页面的代码


<label for='my_file' class="theme-color">
  <mu-icon left value="backup"></mu-icon>
  修改头像
</label>
<input type="file" ref="upload" name="avatar" id='my_file' style="display:none;" accept="image/jpg" @change="changeAvatar" />

axios接口


let ChangeAvatar = (img) => axios({
  url: '/user/changeavatar',
  method: 'post',
  anync: true,
  contentType: false,
  processData: false,
  data: img
})

js部分调用封装的接口


  methods: {
    changeAvatar (event) {
      let img = event.target.files[0];
      let size = img.size;
      if (size > 3145728) {
        alert('请选择3M以内的图片!');
        return false;
      }
      let Form = new FormData();
      Form.append('avatar', img, this.avatar_name);
      API.ChangeAvatar(Form)
        .then((response) => {
          console.log(response)
        })
        .catch((error) => {
          console.log(error)
        })
    }
  }
  • 在这里我并没有用form方式,而是将input隐藏,用label绑定input,当我们点击label的时候,也就点击了input
  • 我将请求封装在了另一个文件里,为ChangeAvatar()函数,如果不封装,按常规写法一样是可以的
  • Form.append('avatar', img, this.avatar_name);第一个参数为input的name,第二个参数为文件对象,第三个参数为文件的名字
  • ajax new FormData() 方法提交文件时,不能用data:{a:1}的键值对方法提交,应当直接将文件对象提交data:FormData

后台node代码


const fileUpload = require('express-fileupload');
app.use(fileUpload());

app.post('/user/changeavatar', function(req, res) {
  console.log(req.files); // the uploaded file object
  let avatar = req.files.avatar;

  // Use the mv() method to place the file somewhere on your server
  avatar.mv('dist/static/img/avatar/'+req.files.avatar.name+'.jpg', function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });
})

代码运行,成功将图片上传到了指定目录

来源:https://segmentfault.com/a/1190000015950334

猜你喜欢

转载自blog.csdn.net/w1366352655/article/details/85118846