Java将微信上传的图片MultipartFile存为URL,将URL返回给微信小程序,并显示到微信小程序的<image>中渲染,给出Java和微信小程序的详细代码
时间: 2024-05-07 19:21:42 浏览: 18
Java代码
```java
@RestController
public class ImageUploadController {
private static final String UPLOAD_DIR = "/uploads/";
@Autowired
private ServletContext servletContext;
@PostMapping("/upload")
public String uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
String ext = filename.substring(filename.lastIndexOf('.') + 1);
String storedFilename = UUID.randomUUID().toString() + "." + ext;
String storedDir = servletContext.getRealPath(UPLOAD_DIR);
Path storedPath = Paths.get(storedDir + storedFilename);
Files.copy(file.getInputStream(), storedPath, StandardCopyOption.REPLACE_EXISTING);
String url = "/uploads/" + storedFilename;
return url;
}
}
```
微信小程序代码
```html
<view class="container">
<form>
<button type="button" bindtap="chooseImage">选择图片</button>
<button type="button" bindtap="uploadImage">上传图片</button>
</form>
<image src="{{imageUrl}}" mode="aspectFit" />
</view>
```
```javascript
Page({
data: {
imageUrl: '',
file: null
},
chooseImage: function () {
var that = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
that.setData({
imageUrl: res.tempFilePaths[0],
file: res.tempFiles[0]
})
}
})
},
uploadImage: function () {
var that = this;
wx.uploadFile({
url: 'http://localhost:8080/upload',
filePath: that.data.imageUrl,
name: 'file',
success: function (res) {
that.setData({
imageUrl: 'http://localhost:8080' + res.data
})
}
})
}
})
```