50
所学时间:320分钟
博客量:1
代码量:几百
所学知识:高级英语,
@RestController
@RequestMapping("/common")
@CrossOrigin(origins = "*", maxAge = 3600)
public class CommonController {
@Value("${images.path}")
private String basePath;
@PostMapping("/upload")
public CommonDto<String> upload(
@RequestParam("module") String module,
@RequestParam("file") MultipartFile file
) {
if (file.isEmpty()) {
throw new RuntimeException("文件不能为空");
}
try {
String fileName = UUID.randomUUID() +
file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
File dest = new File(basePath + fileName);
file.transferTo(dest);
return CommonDto.success(fileName);
} catch (Exception e) {
throw new RuntimeException("上传失败: " + e.getMessage());
}
}
@GetMapping("/download")
public void download(@RequestParam String name, HttpServletResponse response) throws FileNotFoundException {
try {
FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
ServletOutputStream outputStream = response.getOutputStream();
String contentType = "image/jpeg";
if (name.endsWith(".png")) {
contentType = "image/png";
} else if (name.endsWith(".gif")) {
contentType = "image/gif";
}
response.setContentType(contentType);
int len;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
outputStream.flush();
}
outputStream.close();
fileInputStream.close();
} catch (Exception e) {
throw new RuntimeException("文件下载失败", e);
}
}
}
浙公网安备 33010602011771号