詳解Vue+axios+Node+express實現(xiàn)文件上傳(用戶頭像上傳)
更新時間:2018年08月10日 10:15:45 作者:ZONE_98F
這篇文章主要介紹了詳解Vue+axios+Node+express實現(xiàn)文件上傳(用戶頭像上傳),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
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()函數(shù),如果不封裝,按常規(guī)寫法一樣是可以的
- Form.append('avatar', img, this.avatar_name);第一個參數(shù)為input的name,第二個參數(shù)為文件對象,第三個參數(shù)為文件的名字
- 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
代碼運行,成功將圖片上傳到了指定目錄
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue 中 beforeRouteEnter 死循環(huán)的問題
這篇文章主要介紹了vue beforeRouteEnter 死循環(huán)的問題,在文章末尾給大家補充介紹了vue中beforeRouteEnter使用的誤區(qū),需要的朋友可以參考下2019-04-04vue3+ts+vite打包后靜態(tài)資源404無法加載js和css問題解決辦法
這篇文章主要給大家介紹了關于vue3+ts+vite打包后靜態(tài)資源404無法加載js和css問題的解決辦法,文中通過代碼以及圖文介紹的非常詳細,對大家的學習或者工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-04-04詳解如何在Vue3使用<script lang=“ts“ setup>語法糖
本文主要介紹了在Vue3使用<script lang=“ts“ setup>語法糖,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06vue 數(shù)據(jù)雙向綁定的實現(xiàn)方法
這篇文章主要介紹了vue 數(shù)據(jù)雙向綁定的實現(xiàn)方法,幫助大家更好的理解和學習使用vue框架,感興趣的朋友可以了解下2021-03-03