图片上传功能
- 首先记录一下将本地图片转换成网络可以访问的地址,写一个配置类实现WebMvcConfigurer接口,重写addResourceHandlers方法,如图:
其中 /images/** 将代替本地磁盘路径 F:/workspaces/images/cartoon/
举个例子:
访问 http://localhost:8082/images/user/icons/8.png
相当于访问本地路径 F:\workspaces\images\cartoon\user\icons\8.png
- FormData对象来存储图片,在如果直接打印 console.log(formData) 的话会前台会显示为空,而后台却可以正常接收到数据,前台如果想要打印信息的话 console.log(formData.get(‘file’))
前台
//<template>
<el-upload class="avatar-uploader"
action="123"
:http-request="upLoad"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="headUrl"
:src="headUrl"
class="avatar">
<i v-else
class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
//<script>
upLoad(file) {
let formData = new FormData()
formData.append('file', file.file)
systemManage.upload(formData).then(res => {
this.headUrl = res.data
})
}
//app.js
// 上传头像
upload(obj) {
let data = obj
return axios({
url: serverUrl + '/home/userManagement/upload',
method: 'post',
headers: {
'Content-Type': 'multipart/form-data'
// 'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
})
}
后台
public String upload(MultipartFile file) {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取后缀
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
fileName = System.currentTimeMillis() + "." + suffix;
String basePath = "F:\\workspaces\\images\\cartoon\\" ;
String relativePath = "temp\\user\\icons";
String path = basePath + relativePath + File.separator + fileName;
Util.uploadImage(path,file);
String imageUrl = "http://localhost:8082/images/" + relativePath + File.separator + fileName;
imageUrl = imageUrl.replace("\\","/");
return imageUrl;
}
/**
* 上传图片
* @param path 图片存储本地磁盘位置
* @param file 图片
*/
public static void uploadImage(String path, MultipartFile file){
File newFile = new File(path);
// 可能目录不存在,就创建
newFile.getParentFile().mkdirs();
try {
file.transferTo(newFile);
System.out.println("上传图片成功");
}catch (Exception e){
System.out.println("上传图片失败");
e.printStackTrace();
}
}