跳至主要内容

T13_0901

上傳/下載圖片時用本身圖片名稱+(_repaired.jpg) ✅

下載時中文名稱的圖片無法下載:(✅) image

原始程式碼:

@RestController
@RequestMapping("/download")
public class DownloadController {
@GetMapping
public ResponseEntity<byte[]> proxyDownload(@RequestParam("url") String fileUrl,@RequestParam("filename") String filename) {
try {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0"); // 防止被拒絕存取

try (InputStream is = conn.getInputStream()) {
byte[] content = is.readAllBytes();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
.contentType(MediaType.APPLICATION_OCTET_STREAM).body(content);
}
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.internalServerError().body(null);
}
}
}

修正後程式碼:

@RestController
@RequestMapping("/download")
public class DownloadController {
@GetMapping
public ResponseEntity<byte[]> proxyDownload(@RequestParam("url") String fileUrl,@RequestParam("filename") String filename) {
try {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0"); // 防止被拒絕存取
InputStream is = conn.getInputStream();
try {
byte[] content = is.readAllBytes();

// 英文備用檔名
String asciiFilename = "download.jpg";
// 中文檔名 encode
String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
String contentDisposition = "attachment; filename=\"" + asciiFilename + "\"; filename*=UTF-8''"+ encodedFilename;

ResponseEntity<byte[]> responseEntity = ResponseEntity.ok()
.header("Content-Disposition", contentDisposition)
.contentType(MediaType.APPLICATION_OCTET_STREAM).body(content);

if (is != null) {
is.close();
}
return responseEntity;
} catch (Throwable throwable) {
if (is != null) {
try {
is.close();
} catch (Throwable throwable1) {

throwable.addSuppressed(throwable1);
}
}
throw throwable;
}
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.internalServerError().body(null);
}
}
}

小小的修正一下歷史圖片的手機版(header)的文字大小