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接口node

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

js部分調用封裝的接口ios

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!');
  });
})

代碼運行,成功將圖片上傳到了指定目錄ajax

相關文章
相關標籤/搜索