Struts File Download
Download steps:
(1) get the file name of the file to be downloaded. encode the file, because the file upload is submitted by get by default.
(2) Business Method for file download and submission
(3) method for returning a file stream
(4) download the displayed file name
File Download list:
| No. |
File Name |
Operation |
| $ {V. count} |
$ {FileName} |
Download |
Action class used for File Download
Package cn. itcast. download; import java. io. file; import java. io. inputStream; import java. io. unsupportedEncodingException; import java.net. URLEncoder; import javax. servlet. http. httpServletRequest; import org. apache. struts2.ServletActionContext; import com. opensymphony. xwork2.ActionSupport; public class DownloadAction extends ActionSupport {public String list () {// obtain the target file String path = ServletActionContext. getServletContext (). getRealPath (/upload); File file = new File (path); String [] fileNames = file. list (); HttpServletRequest request = ServletActionContext. getRequest (); request. setAttribute (fileNames, fileNames); return list;} // step 1 of File Download. get the name of the file to be downloaded. private String fileName; public void setFileName (String fileName) {// process the passed parameters in Chinese (get is submitted by default) try {fileName = new String (fileName. getBytes (ISO8859-1), UTF-8);} catch (UnsupportedEncodingException e) {throw new RuntimeException (e);} this. fileName = fileName;} // 2. download submitted business method public String down () {return download;} // 3. method for returning the file stream public InputStream getAttrInputStream () {return ServletActionContext. getServletContext (). getResourceAsStream (/upload/+ fileName);} // 4. download the public String getDownFileName () {try {fileName = URLEncoder. encode (fileName, UTF-8);} catch (UnsupportedEncodingException e) {throw new RuntimeException (e);} return fileName ;}}Struts configuration file: corresponds to the method name in the action class
/{1}. jsp
Application/octet-stream
AttrInputStream
Attachment; filename =$ {downFileName}
1024