1.如图片上传,后端需要前端传formData类型数据的情况下
<el-button type="primary" @click="uploadFile2()">点击上传</el-button>
<input type="file" @change="fileValueChange2()" ref="uploadFile2" style="display:none;">
enctype="multipart/form-data" 可添加到input
我们使用原生input的方式来实现。
uploadFile2(e){
// 当点击button按钮后会触发此事件
// 作用就是打开文件上传弹框
this.$refs.uploadFile2.click()
},
fileValueChange2(e){
// 选中文件后,会触发input的change事件,即会进入此函数
var formData = new FormData()
// this.$refs.uploadFile2是vue中获取dom元素的方法
// 通过files就可以拿到所有上传的文件,如果是多个文件循环即可
//this.$refs.uploadFile2.files[0] 或者 e.target.files[0]
formData.append( 'file',this.$refs.uploadFile2.files[0])
// 必须设置请求类型
formData.append( 'type', "head");
// 如果需要传id的情况下,参考下面代码
formData.append( 'id', this.id);
// 配置完成后,只需要向后台传入formData 变量即可
insertNavigationUpload(formData).then(res=>{
console.log('简单吧')
//最后清除上传的文件
this.$refs.uploadFile2.value = ''
})
},
接口的封装
export const tMessageNotification = data =>{
return request({
url:'/tMessageNotification/upload',
method: 'POST',
data,
headers: {'Content-Type': 'application/json'},
})
}
结束。。。。