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!');
});
})
- 在這里我並沒有用multer,而是用別人的npm包express-fileupload
代碼運行,成功將圖片上傳到了指定目錄