[英]Can Spring Boot set the name of a file being downloaded from a controller endpoint?
Java 11 和 Spring 在此處啟動 2.5.x。 我知道我可以設置 controller 來返回文件的內容,如下所示:
@GetMapping(
value = "/get-image-with-media-type",
produces = MediaType.IMAGE_JPEG_VALUE
)
public @ResponseBody byte[] getImageWithMediaType() throws IOException {
InputStream in = getClass()
.getResourceAsStream("/path/to/some/image.jpg");
return IOUtils.toByteArray(in);
}
但是如果我想控制發回的文件名呢? 例如,在服務器端,文件名可能存儲為“ image.jpg ”,但說我想讓它返回為“ <userId>-<YYYY-mm-DD>-image.jpg
”,其中<userId>
是發出請求的經過身份驗證的用戶的用戶 ID,其中<YYYY-mm-DD>
是發出請求的日期?
例如,如果用戶 123 在 2021 年 12 月 10 日提出請求,則文件將下載為“ 123-2021-12-10-image.jpg ”,如果用戶 234 在 2022 年 1 月 17 日提出請求,它將下載為“ 234-2022-01-17-image.jpg ”。 這是否可以在 Spring/Java/服務器端進行控制,還是由 HTTP 客戶端(瀏覽器、PostMan 等)來決定文件名?
請試試這個,內聯評論:
package com.example;
import java.io.IOException;
import java.security.Principal;
import java.util.Date;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class SomeController {
@GetMapping(
value = "/get-image-with-media-type",
produces = MediaType.IMAGE_JPEG_VALUE
) // we can inject user like this (can be null, when not secured):
public ResponseEntity<byte[]> getImageWithMediaType(Principal user) throws IOException {
// XXXResource is the "spring way", FileSystem- alternatively: ClassPath-, ServletContext-, ...
FileSystemResource fsr = new FileSystemResource("/path/to/some/image.jpg");
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set(HttpHeaders.CONTENT_DISPOSITION,
// for direct downlad "inline", for "save as" dialog "attachment" (browser dependent)
// filename placeholders: %1$s: user id string, 2$tY: year 4 digits, 2$tm: month 2 digits, %2$td day of month 2 digits
String.format("inline; filename=\"%1$s-%2$tY-%2$tm-%2$td-image.jpg\"",
// user name, current (server) date:
user == null ? "anonymous" : user.getName(), new Date()));
// and fire:
return new ResponseEntity<>(
IOUtils.toByteArray(fsr.getInputStream()),
responseHeaders,
HttpStatus.OK
);
}
}
相關參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.