|
@@ -0,0 +1,72 @@
|
|
|
+package com.sky.ioc.controller.download;
|
|
|
+
|
|
|
+import io.swagger.annotations.Api;
|
|
|
+import io.swagger.annotations.ApiOperation;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.core.io.ClassPathResource;
|
|
|
+import org.springframework.util.AntPathMatcher;
|
|
|
+import org.springframework.web.bind.annotation.GetMapping;
|
|
|
+import org.springframework.web.bind.annotation.PathVariable;
|
|
|
+import org.springframework.web.bind.annotation.RestController;
|
|
|
+import org.springframework.web.servlet.HandlerMapping;
|
|
|
+
|
|
|
+import javax.servlet.http.HttpServletRequest;
|
|
|
+import javax.servlet.http.HttpServletResponse;
|
|
|
+import java.io.*;
|
|
|
+import java.net.URLEncoder;
|
|
|
+
|
|
|
+@Api(tags = "文件下载")
|
|
|
+@Slf4j
|
|
|
+@RestController
|
|
|
+public class DownloadController {
|
|
|
+
|
|
|
+ // 文件存放目录
|
|
|
+ private final String prefix = "/static";
|
|
|
+
|
|
|
+
|
|
|
+ @ApiOperation("文件下载")
|
|
|
+ @GetMapping("/download/{path}/**")
|
|
|
+ public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable("path") String path) {
|
|
|
+
|
|
|
+ try {
|
|
|
+ String filePath = prefix + "/" + path + "/" + extractPathFromPattern(request);
|
|
|
+ ClassPathResource classPathResource = new ClassPathResource(filePath);
|
|
|
+ File file = classPathResource.getFile();
|
|
|
+ if (!file.exists()) {
|
|
|
+ throw new RuntimeException("文件不存在");
|
|
|
+ }
|
|
|
+ String filename = file.getName();
|
|
|
+ // 获取文件后缀名
|
|
|
+ String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
|
|
|
+
|
|
|
+ // 将文件写入输入流
|
|
|
+ FileInputStream fileInputStream = new FileInputStream(file);
|
|
|
+ InputStream fis = new BufferedInputStream(fileInputStream);
|
|
|
+ byte[] buffer = new byte[fis.available()];
|
|
|
+ fis.read(buffer);
|
|
|
+ fis.close();
|
|
|
+
|
|
|
+ response.reset();
|
|
|
+ response.setCharacterEncoding("UTF-8");
|
|
|
+ response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
|
|
|
+ response.addHeader("Content-Length", "" + file.length());
|
|
|
+ OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
|
|
|
+ response.setContentType("application/octet-stream");
|
|
|
+ outputStream.write(buffer);
|
|
|
+ outputStream.flush();
|
|
|
+ } catch (Exception e) {
|
|
|
+
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+ private String extractPathFromPattern(final HttpServletRequest request) {
|
|
|
+ String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
|
|
|
+ String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
|
|
+ return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+
|
|
|
+}
|