struts2_文件下载(乱码问题解决)

在下载过程中经常出现的问题就是关于下载文件所在路径及文件实体上,多家注意就能弥补

 

FileDownloadAction.java

package hs.struts2.filedownload.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.struts2.ServletActionContext;

/**
 * struts2文件下载
 */
public class FileDownloadAction {
	//下载的文件名
	private String filename="";
	//用于解决下载中中文乱码问题
	public String getFilename() throws UnsupportedEncodingException {
		return new String(filename.getBytes("gbk"),"iso-8859-1");
	}

	public void setFilename(String filename) throws UnsupportedEncodingException {
		this.filename = new String(filename.getBytes("iso-8859-1"));
	}
	
	public InputStream getDownloadFile() throws FileNotFoundException, UnsupportedEncodingException{
		ServletActionContext.getResponse().setContentType("application/x-msdownload");
		//路径及下载文件实体
		FileInputStream fis =new FileInputStream(new File("F://test//"+filename));
		ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment;filename="+getFilename());
		return fis;
	}
	//文件下载
	public String execute(){
		return "success";
	}
	
}

 

 

 

filedownload.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"  %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>struts2文件下载</title>
  </head>
  
  <body>
  		<a href="download.action?filename=abc.rar">abc.rar</a>
  		<a href="download.action?filename=<%=java.net.URLEncoder.encode("测试.rar") %>">测试.rar</a>
  </body>
</html>

 

 

struts.properties

struts.multipart.maxSize=2048000000

struts.multipart.saveDir=/temp
#字符集设置
struts.i18n.encoding=GBK

 

struts.xml

 

	<!-- struts2文件下载 -->
		<action name="download" class="hs.struts2.filedownload.action.FileDownloadAction">
			<result name="success" type="stream">
				<param name="inputName">downloadFile</param>
			</result>
		</action>
 

体会:

一定要注意下载路径下有相关文件,如果没有则会出现许多莫名奇怪的问题!

你可能感兴趣的:(java,apache,html,jsp,struts)