文件处理

返回图片思路 1

Spring MVC: How to return image in @ResponseBody? - Stack Overflow

1
2
3
4
5
6
@ResponseBody
@RequestMapping(value = "/photo2", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto() throws IOException {
InputStream in = servletContext.getResourceAsStream("/images/no_image.jpg");
return IOUtils.toByteArray(in);
}
1
2
3
4
5
6
7
8
9
// JavaScript
export function getcaptcha(params) {
return request({
url: '/api/user/getcaptcha',
method: 'get',
responseType: 'blob',
params,
});
}

返回图片思路 2

将图片作为 base64 字符串返回,前端渲染 base64 即可。

1
2
3
4
5
6
7
8
// 引入 hutool 的验证码功能
@Override
public String getCaptcha(String captchaKey) {
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(160, 80);
String captchaCode = lineCaptcha.getCode();
codeCache.set(captchaKey, captchaCode, Duration.ofMinutes(5).getSeconds());
return lineCaptcha.getImageBase64Data();
}

spring 异步处理上传的文件时,自动删除问题