package com.example.filedownload;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
@RestController
public class FileDownloadController {
@GetMapping("/download")
public ResponseEntity<InputStreamResource> downloadFile(@RequestParam String fileUrl) {
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // HTTP OK
InputStream inputStream = connection.getInputStream();
String fileName = getFileNameFromUrl(fileUrl);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
return new ResponseEntity<>(new InputStreamResource(inputStream), headers, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
private String getFileNameFromUrl(String fileUrl) {
String path = new URL(fileUrl).getPath();
return path.substring(path.lastIndexOf('/') + 1);
}
}

被折叠的 条评论
为什么被折叠?



