| | |
| | | import org.springframework.web.multipart.MultipartFile; |
| | | |
| | | import javax.servlet.http.HttpServletResponse; |
| | | import java.io.File; |
| | | import java.io.FileInputStream; |
| | | import java.io.IOException; |
| | | import java.io.OutputStream; |
| | | import java.io.*; |
| | | import java.net.URLEncoder; |
| | | import java.nio.charset.StandardCharsets; |
| | | import java.nio.file.Files; |
| | | import java.util.HashMap; |
| | | import java.util.UUID; |
| | |
| | | @PostMapping("/upload") |
| | | public RestResponse uploadFile(MultipartFile file) throws Exception |
| | | { |
| | | // 检查文件是否为空 |
| | | if (file.isEmpty()) { |
| | | return RestResponse.fail(500, "上传的文件为空"); |
| | | } |
| | | // // 检查文件是否为空 |
| | | // if (file.isEmpty()) { |
| | | // return RestResponse.fail(500, "上传的文件为空"); |
| | | // } |
| | | try { |
| | | // 获取文件名 |
| | | String originalFileName = StringUtils.cleanPath(file.getOriginalFilename()); |
| | |
| | | throw new RuntimeException("文件不存在"); |
| | | } |
| | | |
| | | // 读取文件内容 |
| | | byte[] fileContent = Files.readAllBytes(file.toPath()); |
| | | |
| | | // 设置响应头 |
| | | response.setHeader("Content-Disposition", "attachment; filename=" + fileName); |
| | | String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()); |
| | | response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName); |
| | | response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); |
| | | response.setContentLengthLong(file.length()); // 设置文件大小,便于浏览器显示进度 |
| | | |
| | | // 将文件内容写入响应输出流 |
| | | response.getOutputStream().write(fileContent); |
| | | response.getOutputStream().flush(); |
| | | |
| | | // 流式传输:使用缓冲流分块读写,避免一次性加载整个文件到内存 |
| | | try (InputStream in = new BufferedInputStream(new FileInputStream(file)); |
| | | OutputStream out = new BufferedOutputStream(response.getOutputStream())) { |
| | | |
| | | byte[] buffer = new byte[8192]; // 8KB缓冲区 |
| | | int len; |
| | | // 循环读取文件内容,每次读8KB,写入响应输出流 |
| | | while ((len = in.read(buffer)) != -1) { |
| | | out.write(buffer, 0, len); |
| | | } |
| | | out.flush(); // 确保最后一部分数据被写出 |
| | | } catch (IOException e) { |
| | | throw new RuntimeException("文件下载失败", e); |
| | | } |
| | | |
| | | |
| | | // // 读取文件内容 |
| | | // byte[] fileContent = Files.readAllBytes(file.toPath()); |
| | | // |
| | | // // 设置响应头 |
| | | // response.setHeader("Content-Disposition", "attachment; filename=" + fileName); |
| | | // response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); |
| | | // |
| | | // |
| | | // |
| | | // // 将文件内容写入响应输出流 |
| | | // response.getOutputStream().write(fileContent); |
| | | // response.getOutputStream().flush(); |
| | | } |
| | | |
| | | } |