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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM