前段事件,学习了下springboot的一些知识,现在复习一下,用springboot2结合小程序,实现一下前后端头像上传的功能。废话不多说,看具体代码,看不懂的小伙伴记得留言,我会一一解答。
springboot代码:
public class UploadUtils {
public static File getFileDir(String userId) {
String filePath = "/Users/wudengyao/111111springboot_upload/";
String childPath = userId+"/images/";
//如果上传目录为/static/images/upload/,则可以如下获取
File upload=new File(filePath,childPath);
if(!upload.exists()){
upload.mkdirs();
//在开发测试模式时,得到地址为:{项目跟目录}/target/static/images/upload/
//在打成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/
}
System.out.println(upload.getAbsolutePath());
return upload;
}
}
/**
* 图片上传
* @param userId
* @param file
* @return
*/
@PostMapping(value ="/upload",produces = {"application/json;charset=UTF-8"})
@ResponseBody
public Object upload(String userId,@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseResultUtil.fail(ResponseResultEnum.UNKNOWN.getCode(),
"上传失败,请选择文件");
}
String fileName = file.getOriginalFilename();
File upload = UploadUtils.getFileDir(userId);
File dest = new File(upload,fileName);
try {
file.transferTo(dest);
LOGGER.info("上传成功");
System.out.println(userId+"/images/"+fileName);
User user = new User();
user.setId(Integer.parseInt(userId));
user.setAvator(userId+"/images/"+fileName);
userService.updateUser(user);
return ResponseResultUtil.success("上传成功",user);
} catch (IOException e) {
LOGGER.error(e.toString(), e);
}
return ResponseResultUtil.fail(ResponseResultEnum.UNKNOWN.getCode(),
"上传失败");
}
这里头像上传成功之后,还有一部更新数据库用户头像的操作
User user = new User();
user.setId(Integer.parseInt(userId));
user.setAvator(userId+"/images/"+fileName);
userService.updateUser(user);
如上图,这里要提的就是springboot2.x虚拟路径的设置,我这里把图片上传保存在了本地电脑的/Users/wudengyao/111111springboot_upload/目录下,然后具体路径再根据用户的userid建立子文件夹,虚拟路径设置完之后就能在本地通过url直接调用图片了
小程序端代码:
/**
* 上传头像
*/
upload(userId,path, sCallback) {
wx.uploadFile({
url: config.api_base_url + 'user/upload?userId=' + userId,
filePath: path,
name: 'file',
header: {
"Content-Type": "application/x-www-form-urlencoded;text/html; charset=utf-8"
},
success(res) {
const data = JSON.parse(res.data);
console.log(config.api_base_url + data.data.avator);
sCallback(data);
}
})
}
小程序端的代码,就是请求的时候传递一个用户id和文件路径(由wx.chooseImage返回)
page页面代码:
uploadAvator(){
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success:(res)=>{
const tempFilePaths = res.tempFilePaths
console.log(tempFilePaths);
uploadModel.upload(this.data.user.id, tempFilePaths[0], (res) => {
this.setData({
avator: config.api_base_url + res.data.avator,
})
})
}
})
}
wxml代码
<button bindtap="uploadAvator">上传头像</button>
<image src="{{avator}}"></image>