스프링 컨트롤러에서 파일 다운로드
웹사이트에서 PDF를 다운로드해야 하는 요건이 있습니다.PDF는 코드 내에서 생성되어야 하는데, 프리마커와 iText와 같은 PDF 생성 프레임워크의 조합이라고 생각했습니다.더 좋은 방법은?
단, Spring Controller를 통해 파일을 다운로드하려면 어떻게 해야 합니까?
@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
public void getFile(
@PathVariable("file_name") String fileName,
HttpServletResponse response) {
try {
// get your file as InputStream
InputStream is = ...;
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (IOException ex) {
log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
throw new RuntimeException("IOError writing file to output stream");
}
}
으로 말하면, 반적으,,,가 있을 때,response.getOutputStream()
에다 아무거나 쓸 수 생성된 PDF를 생성기에 저장할 장소로 이 출력 스트림을 전달할 수 있습니다.하고 있는 있는 는, 「」, 「」, 「」를 설정할 수 .
response.setContentType("application/pdf");
ResourceHttpMessageConverter에서 봄에 내장된 지원을 사용하여 이를 스트리밍할 수 있었습니다.그러면 mime-type을 판별할 수 있는 경우 content-length 및 content-type이 설정됩니다.
@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)
@ResponseBody
public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
return new FileSystemResource(myService.getFileFor(fileName));
}
응답에 직접 파일을 쓸 수 있어야 합니다.뭐랄까
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"somefile.pdf\"");
다음 .response.getOutputStream()
. . . . . . . .를 잊지 response.flush()
마지막엔 그걸로 충분할 거야
3.0에서는 3.을 사용할 수 있습니다.HttpEntity
object.return 、이것을사용하면컨트롤러는필요없습니다.HttpServletResponse
오브젝트 테스트에 도움이 됩니다.이것을 제외하고, 이 대답은 Infeligo의 대답과 상대적이다.
pdf 프레임워크의 반환값이 바이트 배열인 경우(다른 반환값은 내 답변의 두 번째 부분을 참조하십시오).
@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
@PathVariable("fileName") String fileName) throws IOException {
byte[] documentBody = this.pdfFramework.createPdf(filename);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_PDF);
header.set(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + fileName.replace(" ", "_"));
header.setContentLength(documentBody.length);
return new HttpEntity<byte[]>(documentBody, header);
}
PDF documentBbody
Framework()의 반환 유형이 바이트 배열이 아닌 경우(및ByteArrayInputStream
그럼 먼저 바이트 배열로 하지 않는 것이 좋습니다.대신 다음을 사용하는 것이 좋습니다.
InputStreamResource
,PathResource
(Spring 4.0 이후) 또는FileSystemResource
,
를 제시하겠습니다.FileSystemResource
:
@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
@PathVariable("fileName") String fileName) throws IOException {
File document = this.pdfFramework.createPdf(filename);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_PDF);
header.set(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + fileName.replace(" ", "_"));
header.setContentLength(document.length());
return new HttpEntity<byte[]>(new FileSystemResource(document),
header);
}
다음과 같은 경우:
- 않다
byte[]
응답으로 전송하기 전에 InputStream
;- MIME 유형 및 파일 이름을 완전히 제어하고 싶다.
- 것을 먹다
@ControllerAdvice
예외를 인정(또는 인정 안 함)
필요한 코드는 다음과 같습니다.
@RequestMapping(value = "/stuff/{stuffId}", method = RequestMethod.GET)
public ResponseEntity<FileSystemResource> downloadStuff(@PathVariable int stuffId)
throws IOException {
String fullPath = stuffService.figureOutFileNameFor(stuffId);
File file = new File(fullPath);
long fileLength = file.length(); // this is ok, but see note below
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentType("application/pdf");
respHeaders.setContentLength(fileLength);
respHeaders.setContentDispositionFormData("attachment", "fileNameIwant.pdf");
return new ResponseEntity<FileSystemResource>(
new FileSystemResource(file), respHeaders, HttpStatus.OK
);
}
상세정보 : 우선 헤더는 HTTP 1.1 RFC에 따라 옵션입니다.그래도 값을 제공할 수 있다면 더 좋습니다.이러한 가치를 얻으려면File#length()
일반적인 경우로 충분하기 때문에 안전한 디폴트 선택입니다.
그러나 매우 구체적인 시나리오에서는 속도가 느릴 수 있으며, 이 경우 데이터를 즉석에서 계산하지 않고 미리 저장(예: DB)해야 합니다.느린 시나리오에는 파일이 매우 큰 경우, 특히 리모트시스템에 있는 경우 또는 데이터베이스와 같은 보다 상세한 경우 등이 있습니다.
InputStreamResource
DB에서 데이터를 가져오는 등 리소스가 파일이 아닌 경우 를 사용해야 합니다. 예:
InputStreamResource isr = new InputStreamResource(...);
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
이 코드는 jsp의 링크를 클릭하면 스프링 컨트롤러에서 자동으로 파일을 다운로드 할 수 있습니다.
@RequestMapping(value="/downloadLogFile")
public void getLogFile(HttpSession session,HttpServletResponse response) throws Exception {
try {
String filePathToBeServed = //complete file name with path;
File fileToDownload = new File(filePathToBeServed);
InputStream inputStream = new FileInputStream(fileToDownload);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment; filename="+fileName+".txt");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
} catch (Exception e){
LOGGER.debug("Request could not be completed at this moment. Please try again.");
e.printStackTrace();
}
}
수작업으로 아무것도 하지 말고 대신 프레임워크에 작업을 위임하십시오.
ResponseEntity<Resource>
Content-Type
- ★★
Content-Disposition
다음 중 하나:- 파일명
- 유형
inline
브라우저에서 미리 보기를 강제하다attachment
다운로드를 강요하다
@Controller
public class DownloadController {
@GetMapping("/downloadPdf.pdf")
// 1.
public ResponseEntity<Resource> downloadPdf() {
FileSystemResource resource = new FileSystemResource("/home/caco3/Downloads/JMC_Tutorial.pdf");
// 2.
MediaType mediaType = MediaTypeFactory
.getMediaType(resource)
.orElse(MediaType.APPLICATION_OCTET_STREAM);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
// 3
ContentDisposition disposition = ContentDisposition
// 3.2
.inline() // or .attachment()
// 3.1
.filename(resource.getFilename())
.build();
headers.setContentDisposition(disposition);
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
}
설명.
ResponseEntity<Resource>
를 반환하면가 기동하여 적절한 응답을 씁니다.
resource
하다
응용 프로그램 리소스 디렉토리에서 파일을 다운로드해야 하는 경우 내 답변을 확인하십시오. 이 답변은 클래스 경로에서 리소스를 찾는 방법에 대해 설명합니다.
수 하십시오.Content-Type
헤더 세트('파일 시스템리소스'는 콘텐츠유형 json으로 반환된다' 참조).그렇기 때문에 이 답변은 '세팅'을 제안합니다.Content-Type
명쾌하게
명시적으로 지정합니다.
다음과 같은 옵션이 있습니다.
MediaTypeFactory
을 할 수 .MediaType
app에 Resource
도)./org/springframework/http/mime.types
삭제)
필요한 경우 설정:
브라우저에서 강제로 다운로드를 수행하거나 브라우저에서 파일을 미리 보기로 열어야 하는 경우가 있습니다.헤더를 사용하여 다음 요건을 충족할 수 있습니다.
의 첫 "HTTP" 입니다.
inline
페이지 내 할 수 것을 ). ('' ' ' ' ') ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 'attachment
('다른 이름으로 저장' 대화 상자를 표시하는 대부분의 브라우저는 파일 이름 매개 변수(존재하는 경우)의 값으로 미리 채워집니다).
스프링 프레임워크에서는 a를 사용할 수 있습니다.
브라우저에서 파일을 미리 보려면:
ContentDisposition disposition = ContentDisposition
.builder("inline") // Or .inline() if you're on Spring MVC 5.3+
.filename(resource.getFilename())
.build();
강제로 다운로드하려면:
ContentDisposition disposition = ContentDisposition
.builder("attachment") // Or .attachment() if you're on Spring MVC 5.3+
.filename(resource.getFilename())
.build();
주의해서 사용:
한 그 이후로는기 때문에InputStream
한번만 읽을 수 있다, 봄 한 번만읽을 수 있어,봄은 쓰지 않아 잘 안 써진다.Content-Length
헤더 만약 당신이 header를 반환하는 경우 돌아온다.InputStreamResource
(여기 코드(다음은 코드 조각입니다에서 무리다.ResourceHttpMessageConverter
):):
@Override
protected Long getContentLength(Resource resource, @Nullable MediaType contentType) throws IOException {
// Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
// Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
if (InputStreamResource.class == resource.getClass()) {
return null;
}
long contentLength = resource.contentLength();
return (contentLength < 0 ? null : contentLength);
}
그 외의 경우는 정상적으로 동작합니다.
~ $ curl -I localhost:8080/downloadPdf.pdf | grep "Content-Length"
Content-Length: 7554270
아래 코드는 텍스트 파일을 생성하고 다운로드하는 데 도움이 되었습니다.
@RequestMapping(value = "/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> getDownloadData() throws Exception {
String regData = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
byte[] output = regData.getBytes();
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("charset", "utf-8");
responseHeaders.setContentType(MediaType.valueOf("text/html"));
responseHeaders.setContentLength(output.length);
responseHeaders.set("Content-disposition", "attachment; filename=filename.txt");
return new ResponseEntity<byte[]>(output, responseHeaders, HttpStatus.OK);
}
즉시 생각할 수 있는 것은 PDF를 생성하여 코드에서 webapp/downloads/<RANDOM-FILNAME>.pdf에 저장하고 Http ServletRequest를 사용하여 이 파일로 전송하는 것입니다.
request.getRequestDispatcher("/downloads/<RANDOM-FILENAME>.pdf").forward(request, response);
또는 뷰 리졸바 같은 것을 설정할 수 있으면,
<bean id="pdfViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="order" value=”2″/>
<property name="prefix" value="/downloads/" />
<property name="suffix" value=".pdf" />
</bean>
그럼 그냥 돌아와
return "RANDOM-FILENAME";
다음과 같은 솔루션이 효과적입니다.
@RequestMapping(value="/download")
public void getLogFile(HttpSession session,HttpServletResponse response) throws Exception {
try {
String fileName="archivo demo.pdf";
String filePathToBeServed = "C:\\software\\Tomcat 7.0\\tmpFiles\\";
File fileToDownload = new File(filePathToBeServed+fileName);
InputStream inputStream = new FileInputStream(fileToDownload);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
} catch (Exception exception){
System.out.println(exception.getMessage());
}
}
다음과 같은 것
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void getFile(HttpServletResponse response) {
try {
DefaultResourceLoader loader = new DefaultResourceLoader();
InputStream is = loader.getResource("classpath:META-INF/resources/Accepted.pdf").getInputStream();
IOUtils.copy(is, response.getOutputStream());
response.setHeader("Content-Disposition", "attachment; filename=Accepted.pdf");
response.flushBuffer();
} catch (IOException ex) {
throw new RuntimeException("IOError writing file to output stream");
}
}
PDF 를 표시하거나, 예를 다운로드할 수 있습니다.
누구라도 도움이 된다면요Infeligo가 제시한 답변에 따라 할 수 있지만, 강제 다운로드를 위해 이 추가 부분을 코드에 넣기만 하면 됩니다.
response.setContentType("application/force-download");
제 경우 온 디맨드로 파일을 생성하기 때문에 URL도 생성해야 합니다.
저는 이런 식으로 작업합니다.
@RequestMapping(value = "/files/{filename:.+}", method = RequestMethod.GET, produces = "text/csv")
@ResponseBody
public FileSystemResource getFile(@PathVariable String filename) {
String path = dataProvider.getFullPath(filename);
return new FileSystemResource(new File(path));
}
에서의를 매우 중요하다 마임 형식 타입은매우 중요합니다.produces
링크으면일부이기 때문에 링크의 파일명은그리고 그를 사용해야만 한다 그리고 또한, 해당 파일 이름 일부이다.@PathVariable
.
HTML 코드는 다음과 같습니다.
<a th:href="@{|/dbreport/files/${file_name}|}">Download</a>
어디 어디에${file_name}
는 컨트롤러의 Thymeleaf에 의해 생성됩니다.즉,result_20200225.csv 입니다도록 전체 url behing 링크:Thymeleaf에 의해 컨트롤러에서 result_20200225.csv i.e.은, 생성됩니다.따라서 url고 링크 전체가다음과 같습니다.example.com/aplication/dbreport/files/result_20200225.csv
.
링크 브라우저를 클릭한 후 파일을 저장할지 열지를 묻는 메시지가 나타납니다.
이것은 유용한 답변이 될 수 있습니다.
프런트엔드에서 pdf 형식으로 데이터를 내보내도 될까요?
이를 확장하면 content-disposition을 첨부 파일(기본값)로 추가하면 파일이 다운로드됩니다.표시할 경우 인라인으로 설정해야 합니다.
파일을 다운로드하려면 이 파일을 추가해야 합니다.
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename="+"file.txt");
모든 코드:
@Controller
public class FileController {
@RequestMapping(value = "/file", method =RequestMethod.GET)
@ResponseBody
public FileSystemResource getFile(HttpServletResponse response) {
final File file = new File("file.txt");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename="+"file.txt");
return new FileSystemResource(file);
}
}
언급URL : https://stackoverflow.com/questions/5673260/downloading-a-file-from-spring-controllers
'sourcecode' 카테고리의 다른 글
vuej를 사용하여 설치 가능한 PWA를 만드는 방법 (0) | 2022.07.17 |
---|---|
개발 모드에서 이 HTML 템플릿을 컴파일하는 데 Vue가 매우 느림 (0) | 2022.07.17 |
vue.timeout의 구성 요소에 개체 배열 전달 (0) | 2022.07.17 |
JPA의 맵 열거형(고정값 포함)을 지정하시겠습니까? (0) | 2022.07.17 |
컬렉션을 목록으로 변환하는 방법 (0) | 2022.07.17 |