struts2——文件下载自定义文件名,包括中文
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@taglib uri="/struts-tags" prefix="s"%> 4 <!DOCTYPE html> 5 <html> 6 <head> 7 <meta charset="UTF-8"> 8 <title>struts2的一个例子</title> 9 </head> 10 <body> 11 <form action="downloadFile.action" method="post" enctype="multipart/form-data"> 12 文件名:<input type="text" name="fileName" value="CSS"/>.jpg<br/> 13 <input type="submit" value="下载文件"> 14 </form> 15 16 </body> 17 </html>
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4 "http://struts.apache.org/dtds/struts-2.3.dtd"> 5 <struts> 6 <constant name="struts.devMode" value="true"/> 7 <package name="hello" extends="struts-default" namespace="/"> 8 <action name="downloadFile" class="com.xiaostudy.web.DownloadFile" method="downloadFile"> 9 <result name="success" type="stream"> 10 <param name="inputName">fileInputStream</param> 11 <param name="contentDisposition">attachment;filename="${fileName}.jpg"</param> 12 <param name="contentType">application/octet-stream</param> 13 </result> 14 </action> 15 </package> 16 </struts>
1 package com.xiaostudy.web; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.io.UnsupportedEncodingException; 9 10 import org.apache.struts2.ServletActionContext; 11 12 import com.opensymphony.xwork2.ActionSupport; 13 14 public class DownloadFile extends ActionSupport { 15 16 public InputStream fileInputStream; 17 public String fileName; 18 19 public String downloadFile() throws IOException { 20 21 String path = ServletActionContext.getServletContext().getRealPath("/WEB-INF/files/CSS.jpg"); 22 fileInputStream = new FileInputStream(new File(path)); 23 this.fileName = new String(fileName.getBytes(), "ISO8859-1"); 24 25 return SUCCESS; 26 } 27 28 public String getFileName() { 29 return fileName; 30 } 31 public void setFileName(String fileName) { 32 this.fileName = fileName; 33 } 34 public InputStream getFileInputStream() { 35 return fileInputStream; 36 } 37 public void setFileInputStream(InputStream fileInputStream) { 38 this.fileInputStream = fileInputStream; 39 } 40 41 42 }