Struts2를 사용하면 Action
및 Result
이 있습니다.
그래서, 당신은, 임의의 파일을 허용하는 위험 (다운로드 할 파일 struts2를 알려줄 수있는 매개 변수를 전달 download_file.do
당신은 링크의 목록을 생성을 호출, Action
당신의 연결에 매핑 할 필요 어쩌면 파일 이름이 좋을 수도 있습니다).
<s:iterator value="fileList">
<s:a action="download_file">
<s:property value="fileName"/>
<s:text name="my.link"/>
</a>
</s:iterator>
지금에 Action
당신은 평소처럼 fileName
에 대한 세터해야합니다.
execute
메서드에서 fileName을 얻은 다음 InputStream
에서 File
으로 열고 getter
을 입력하십시오. 파일의 크기를 가져오고 다운로드하려는 이름을 원할 수도 있습니다.
InputStream
의 게터가 getFileToDownload
이고 게터가 getFileSize
인 것으로 가정합니다.
당신은 내용 처리에 대한 게터를 제공해야합니다,이 다운로드 한 파일의 이름을 설정합니다, 뭔가 같은 : 또한
public String getContentDisposition() {
return "attachment;filename=\"" + fileName + "\"";
}
그리고 MIME 유형에 대한 게터,
public String getContentType() {
return "text/plain";
}
같은
분명히 MIME을 올바른 유형으로 설정하십시오.
그래서이
public class MyAction extends ActionSupport {
private final File baseDownloadDir = new File("somewhere");
private String fileName;
private InputStream inputStream;
private long fileSize;
@Override
public String execute() throws Exception {
/*
*This is a security hole begging to be exploited.
*A user can submit "../../../../someImportantFile"
*and potentially download arbitrary files from the server.
*You really need to do some validation on the input!
*/
final File fileToDownload = new File(baseDownloadDir, fileName);
fileSize = fileToDownload.length();
inputStream = new FileInputStream(fileToDownload);
return "downloadFile";
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public long getFileSize() {
return fileSize;
}
public InputStream getFileToDownload() {
return inputStream;
}
public String getContentDisposition() {
return "attachment;filename=\"" + fileName + "\"";
}
public String getContentType() {
return "text/plain";
}
}
같은 기본적인 Action
모양 뭔가 그런 다음 결과의 이름을 반환, 그것을 downloadFile
를 호출 할 수 있습니다. 액션 매핑에
당신이 StreamResult
에 그 결과를 매핑 할 필요가, 여기에 XML 예제
당신은 문자 집합을 변경할 수 있습니다
<result name="downloadFile" type="stream">
<param name="inputName">fileToDownload</param>
<param name="contentType">${contentType}</param>
<param name="contentLength">${fileSize}</param>
<param name="contentDisposition">${contentDisposition}</param>
<param name="contentCharSet">UTF-8</param>
<param name="allowCaching">true</param>
</result>
입니다.
시간 내 주셔서 대단히 감사합니다. 친절하게도 한 가지 더 물어 보겠습니다. struts.xml에서 "inputName"& "contentDisposition"매개 변수로 파일을 다운로드 할 수 있습니까? –
다른 매개 변수가 필요합니까? 유일한 _required_ 매개 변수는'inputName'입니다 - [documentation] (http://struts.apache.org/release/2.3.x/docs/stream-result.html)을보십시오. 다른 브라우저는 예상대로 브라우저를 작동시킵니다. –