|
@@ -9,6 +9,8 @@ import org.springframework.http.ResponseEntity;
|
|
|
import org.springframework.web.bind.annotation.*;
|
|
|
|
|
|
import java.io.*;
|
|
|
+import java.net.HttpURLConnection;
|
|
|
+import java.net.URL;
|
|
|
import java.nio.file.Files;
|
|
|
import java.nio.file.Paths;
|
|
|
import java.util.List;
|
|
@@ -85,4 +87,59 @@ public class FileDownloadController {
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+ // 互联网上文件的URL
|
|
|
+ private static final String REMOTE_FILE_URL = "https://static.fuxicarbon.com/userupload/ttt.wav";
|
|
|
+
|
|
|
+ // 缓存下载文件的临时目录(确保这个目录存在并且应用有写入权限)
|
|
|
+ private static final String TEMP_DIR = "/Users/wangmiaomiao/Downloads/";
|
|
|
+
|
|
|
+ // 缓存文件的文件名(可以从URL中解析出来,或者根据需求设置)
|
|
|
+// private static final String CACHED_FILE_NAME = "downloaded_file.zip";
|
|
|
+ private static final String CACHED_FILE_NAME = "ttt.wav";
|
|
|
+
|
|
|
+ @GetMapping("/downloadHttpUrl")
|
|
|
+ public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
|
|
|
+ File cachedFile = new File(TEMP_DIR + CACHED_FILE_NAME);
|
|
|
+
|
|
|
+ // 如果文件不存在,则从互联网上下载
|
|
|
+ if (!cachedFile.exists()) {
|
|
|
+ File tempDir = new File(TEMP_DIR);
|
|
|
+ if (!tempDir.exists()) {
|
|
|
+ tempDir.mkdirs();
|
|
|
+ }
|
|
|
+ downloadFileFromInternet(REMOTE_FILE_URL, cachedFile);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 设置HTTP响应头
|
|
|
+ HttpHeaders headers = new HttpHeaders();
|
|
|
+ headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + CACHED_FILE_NAME + "\"");
|
|
|
+ headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
|
|
|
+ headers.setContentLength(cachedFile.length());
|
|
|
+
|
|
|
+ // 返回文件内容作为响应体
|
|
|
+ InputStream inputStream = Files.newInputStream(cachedFile.toPath());
|
|
|
+ InputStreamResource resource = new InputStreamResource(inputStream);
|
|
|
+
|
|
|
+ return ResponseEntity.ok()
|
|
|
+ .headers(headers)
|
|
|
+ .body(resource);
|
|
|
+ }
|
|
|
+
|
|
|
+ private void downloadFileFromInternet(String fileURL, File destination) throws IOException {
|
|
|
+ URL url = new URL(fileURL);
|
|
|
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
|
|
+ connection.setRequestMethod("GET");
|
|
|
+
|
|
|
+ try (InputStream inputStream = connection.getInputStream();
|
|
|
+ FileOutputStream outputStream = new FileOutputStream(destination)) {
|
|
|
+
|
|
|
+ byte[] buffer = new byte[4096];
|
|
|
+ int bytesRead;
|
|
|
+ while ((bytesRead = inputStream.read(buffer)) != -1) {
|
|
|
+ outputStream.write(buffer, 0, bytesRead);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
}
|