Struts2文件下载中文乱码解决方案

ResourceDownloadAction.java

package csu.soft.boss.action;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;

public class ResourceDownloadAction implements Action {

	private String inputPath;  //服务器端文件名
	
	public String getInputPath() {
		return inputPath;
	}

	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}
	
	private String fileName;  //客户端下载保存文件名
	
	public String getFileName() throws UnsupportedEncodingException {
		String downFileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
		downFileName=URLEncoder.encode(downFileName,"UTF-8");
		return downFileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
	private int flag;
	
	public int getFlag() {
		return flag;
	}

	public void setFlag(int flag) {
		this.flag = flag;
	}

	// inputStream属性的getter方法,StreamResult结果类型使用该属性来读取下载文件的内容
	public InputStream getInputStream() throws Exception{
		//return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
		String filePath="";
		if(flag==1){
			filePath=ServletActionContext.getServletContext().getRealPath("/ProjectAttachments/")+"\\"+inputPath;			
		}else if(flag==2){
			filePath=ServletActionContext.getServletContext().getRealPath("/BaseAttachments/")+"\\"+inputPath;
		}else if(flag==3){
			String postfix=inputPath.substring(inputPath.indexOf("."));
			fileName=fileName+postfix;
			filePath=ServletActionContext.getServletContext().getRealPath("/Resources/")+"\\"+inputPath;
		}
		
		return new FileInputStream(filePath);
		
	}

	public String execute() throws Exception {
		return SUCCESS;
	}

}

struts.xml

<action name="ResourceDownloadAction" class="csu.soft.boss.action.ResourceDownloadAction">
        	<!-- 使用StreamResult结果类型 -->
        	<result name="success" type="stream">
        		<!-- inputName默认值是inputStream,如果action中用于读取下载文件内容的属性名是inputStream,那么可以省略这个参数 -->
        		<param name="inputName">inputStream</param>
        		<param name="contentDisposition">attachment;fileName="${fileName}"</param>
        		<param name="bufferSize">
        			2048
        		</param>
        	</result>
        </action>

projectInfo.jsp

<a href="ResourceDownloadAction?inputPath=${file.savedName}&fileName=${file.realName}&flag=1">${file.realName}</a>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值