(编辑:jimmy 日期: 2024/11/20 浏览:2)
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) }) } }
后台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
代码运行,成功将图片上传到了指定目录
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。