SpringBoo与微信小程序交互
1.1spring图片上传后端代码
Controller类 上传代码,把图片保存到本地
//文件保存在磁盘的地址
@Value("${file.save.path}")
String fileSavePath;
@RequestMapping("upImgs")
public String upImgs(HttpServletRequest request,
@RequestParam("file") MultipartFile myfile,
@RequestParam("desc") String desc) throws IOException {
File fir=new File(fileSavePath);
//不存在则创建文件夹
if(!fir.exists()){
fir.mkdirs();
}
//文件的后缀名
String suffix=myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."));
//新文件名字 为了防止重复加上UUID
String newFileName= UUID.randomUUID().toString().replaceAll("-","")+suffix;
System.out.println("filesavepath:"+fileSavePath+" "+"newFileName:"+newFileName);
//新的文件路径
File newFile=new File(fileSavePath+newFileName);
//把文件写入新的File文件
myfile.transferTo(newFile);
//url路径=http + :// + server名字 + port端口 + /imges/ + newFileName
String url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/images/"+newFileName;
return url;
}
#1.2 微信小程序上传图片代码
通过调用chooseImage的api,调用相应的接口,把图片传输到后端接口保存
fileUpLoad(){
--调用小程序api接口
wx.chooseImage({
success(res){
const tempFilePaths=res.tempFilePaths
wx.uploadFile({
filePath: tempFilePaths[0],
name: 'file',
url: 'http://localhost:8080/img/upImgs',
formData:{
desc:'图片'
},
success(res){
console.log(res.data)
}
})
}
})({
success(res){
console.log(res.tempFiles.tempFilePath)
}
})
}
2.1spring图片返回到前端代码
这里有两种方法,一种是在yml文件里面配置路径映射
spring:
mvc:
static-path-pattern: /imges/**
web:
resources:
static-locations: file:E://test/te1
另外一种是config类
@Configuration
public class ImgConfig implements WebMvcConfigurer {
@Value("${file.save.path}")
String fileSavePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**").
addResourceLocations("file:"+fileSavePath);
}
}
相应的yml文件
file:
save:
path: E:/test/te1/
#2.2 微信小程序图片显示代码
data: {
src:'',
},
showImg(){
const that=this
wx.request({
url: 'http://localhost:8080/img/upImg',
success(res){
that.setData({
src:res.data
})
}
})
},
--wxml代码
<block>
<view>
<button bindtap="showImg">showImg</button>
</view>
<image class="img" src="{{src}}"></image>
</block>
具体效果:
1、
可以通过http访问
上传到文件中
在前端页面显示2054652.jpg图片,直接返回此url
可以成功展示!
我们处理的思路:可以获取文件到本地磁盘,然后数据库存储路径地址,就可以实现图片的上传和返回图片url并且展示的功能