首次使用才了不少坑
效果
本来是不想直接用action上传到后端的,想用http-request="uploadFileRequest"上传,但是在?uploadFileRequest方法中参数File获取不到文件流,file.file和file.raw都不行,就还是用action直接提交上传吧
file参数的值:
直接贴代码看吧
<el-upload
class="avatar-uploader"
limit="1" //最大允许上传个数
//:http-request="uploadFileRequest"
:action="uploadUrl"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
<script>
export default {
name: "addArticle",
setup() {
const imageUrl = ref("");
const editor = ref(null);
const $systemUrl = getCurrentInstance()?.appContext.config.globalProperties.$systemUrl;
const uploadUrl = ref($systemUrl + "/uploadFile");
const handleAvatarSuccess = (res, file) => {
console.log(res)
if(res.success == true){
ElMessage.success(res.msg);
imageUrl.value = URL.createObjectURL(file.raw);
}else{
ElMessage.error(res.msg);
}
}
const uploadFileRequest = (file) => {
//本来是搭配:http-request="uploadFileRequest" 使用 但是获取不到文件file 故作罢
var fd = new FormData() //构造一个 FormData,把后台需要发送的参数都添加进去
fd.append('file', file.file) //传文件
console.log(fd)
uploadFile(fd).then((res) => {
console.log("2"+res)
imageUrl.value = res;
});
}
const beforeAvatarUpload = (file) => {
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
ElMessage.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
ElMessage.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
return {
handleAvatarSuccess,
beforeAvatarUpload,
imageUrl,
uploadFileRequest,
uploadUrl
};
},
};
</script>
后端controller代码
@RequestMapping("/uploadFile")
public Result uploadFile(HttpServletRequest request, MultipartFile file){
return fileUploadService.uploadFile(request, file);
}
|