springBoot上传限制默认为1MB
可以在yml文件中配置
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
//tomcat 映射地址
private String fileUploadUrlStr = “http://127.0.0.1:46585/upload”;
@ApiOperation("图片上传")
@PostMapping("/uPicture")
public CommonResult<String> uploadPicture(@RequestParam("file") MultipartFile file) {
//上传的文件名称
String fileName = file.getOriginalFilename();
System.out.println(fileName);
long size = file.getSize();
//图片保存地址
String filePath = System.getProperty("user.dir") + "/fileImg/" + System.currentTimeMillis() + ".jpg";
log.info("图片路径:" + filePath);
//映射地址+图片名称
String pictureUrl = fileUploadUrlStr + filePath.substring(filePath.lastIndexOf("/"));
File dest = new File(filePath);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
throw new RuntimeException(e);
}
return CommonResult.success(pictureUrl);
}
@GetMapping("/download")
@ApiOperation("下载图片")
public void download(@RequestParam("path") String path, HttpServletResponse response) {
try {
// 1、定义输入流,通过输入流读取文件内容
String filePath = System.getProperty("user.dir") + "/fileImg";
String name = path.substring(path.lastIndexOf("/"));
FileInputStream fileInputStream = new FileInputStream(filePath + name);
// 2、通过response对象,获取到输出流
ServletOutputStream outputStream = response.getOutputStream();
// 3、通过response对象设置响应数据格式(image/jpeg)
response.setContentType("image/jpeg");
int len = 0;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1) {
// 4、通过输入流读取文件数据,然后通过上述的输出流写回浏览器
outputStream.write(bytes, 0, len);
// 刷新
outputStream.flush();
}
// 5、关闭资源
outputStream.close();
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}