vue前端图片上传、回显图片
方法一(基于vue+html):
方法二(基于vue+element):
return{
imgUrl:'http://localhost:8080/mainupfile/photo',//文件上传访问后端的路径
https://blog.csdn.net/fugaoliang/article/details/dialogImageUrl: null,
dialogVisible: false,
uploadDisabled: false,
limitcount: 1,
}
methods:{
/** 回显图片 */
getAssetsFile(url){
return new URL(`../../assets/upload/${url}`, import.meta.url).href
},
/**选择图片*/
handleChange(file, fileList) {
this.uploadDisabled = fileList.length >= this.limitcount;
console.log("this.uploadDisabled", this.uploadDisabled);
return false;
},
/**删除图片*/
handleRemove(file, fileList) {
this.uploadDisabled = fileList.length >= this.limitcount;
console.log("this.uploadDisabled", this.uploadDisabled);
},
/**成功获取图片*/
onSuccess: function (response) {
// this.imgUrl= this.FormList;
this.https://blog.csdn.net/fugaoliang/article/details/dialogImageUrl = response;
//
this.FormList.reason = response
},
}
方法三(基于vue+vant):
从相册中选择
const afterRead = async (file) => {
const modifiedFile = new File([file.file], '.png'); // 修改文件名为 new_filename.jpg
try {
const formData = new FormData();
formData.append('file', modifiedFile);
const response = await axios.post('http://localhost:8080/upphoto/fileUpload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log("图片为:"+response.data);
showToast({
type: 'success',
message: '头像上传成功',
});
photo.value = response.data;
console.log("photo:"+photo.value);
console.log("response.data:"+response.data);
} catch (error) {
console.error('头像上传失败:', error);
showToast({
type: 'fail',
message: '头像上传失败',
});
}
};
图片预览效果的实现:
Element Plus官网实现:
.demo-image__error .image-slot {
font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
font-size: 30px;
}
.demo-image__error .el-image {
width: 100%;
height: 200px;
}
如果不想用官网的方法,就自己定义事件:
//弹出图片层
//逻辑,我这里是使用了ts语法setup
const previewDialogVisible = ref(false);
const previewImageUrl = ref('');
const getAssetsFile=(url: string)=>{
return new URL(`../assets/upload/${url}`, import.meta.url).href;
// return "../assets/upload/"+ url
}
const openPreview = (url: string) => {
previewImageUrl.value = getAssetsFile(url);
previewDialogVisible.value = true;
};