`

struts2 下载与上传 完美解决中文乱码

    博客分类:
  • S2SH
 
阅读更多

2013.08.16 更新

1、struts配置

    <package name="download" namespace="/down" extends="struts-default">
    	<action name="*_*" method="{2}" class="com.lims.core.action.{1}Action">
    		<result name="down" type="stream">
    			<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
    			<param name="inputName">inputStream</param> 
    			<param name="contentDisposition">attachment;filename="${downloadFileName}"</param> 
    			<param name="bufferSize">10240</param>
    		</result>
    	</action>
    </package>

 2、Action

写道
/**
* 项目名称:LIMS_v1
* 类名称:GlobalDownloadAction
* 类描述:
* 创建人:zangzh
* 创建时间:2013-8-16 下午06:48:08
* 修改人:zangzh
* 修改时间:2013-8-16 下午06:48:08
* 修改备注:
* @version
*/
public class GlobalDownloadAction extends BaseStruts2Action implements Preparable,ModelDriven{
private static final long serialVersionUID = 2591642527793106588L;
public Object getModel() {return null;}

private String fileName ; //下载文件名
private InputStream inputStream ; // 下载文件使用流
private String downloadFileName;

/**
*
*/
public String execute() {
String realpath = ServletActionContext.getServletContext().getRealPath("/");
try {
//设置文件名
String postfix = this.fileName.substring(this.fileName.length()-4);
String fn = URLDecoder.decode(this.downloadFileName, "UTF-8")+postfix;
fn = new String(fn.getBytes(),"ISO8859-1");
//文件
File file = new File(realpath+this.fileName);
if(!file.exists()) {
file = new File(realpath+"upload/notice/nofile.txt");
fn = new String("未到找文件.txt".getBytes(),"ISO8859-1");
}
this.setDownloadFileName(fn);
this.setInputStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
return "down";
}

public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public InputStream getInputStream(){
return inputStream;
}

public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getDownloadFileName() {
return downloadFileName;
}
public void setDownloadFileName(String downloadFileName) {
this.downloadFileName = downloadFileName;
}
}

 3、页面 js 请求

	<script type="text/javascript">
		function down(fileName,downloadFileName) {
			var name = encodeURIComponent(encodeURIComponent(downloadFileName));
			window.open("<%=basePath%>down/GlobalDownload_execute.do?fileName="+fileName+"&downloadFileName="+name,"_blank"); 
		}
	</script>

 

 4、这种方式写了通用的下载,但浏览器点击下载后,在弹出窗口中没有点保存,而点击的取消刚会出以下BUG, 未能解决:

ClientAbortException:  java.net.SocketException: Connection reset by peer: socket write error
	at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:358)
	at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:352)
	at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:381)
	at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:370)
	at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:89)

 

 

-------------------这是早期的写法-  比较乱,建议采用上面的-----------------------------------

一、下载

1 、配置文件

<!-- 确认 候选人基本信息 -->

< action name = "hxrBaseInfo_*" class = "hxrBaseInfoAction" method = "{1}" >

    < result name = "down" type = "stream" >

       < param name = "contentType" >

application/octet -stream;charset =ISO8859-1 </ param >

       < param name = "inputName" > inputStream </ param >

<!-- 使用经过转码的文件名作为下载文件名, downloadFileName 属性  

对应 action 类中的方法 getDownloadFileName() -->

        < param name = "contentDisposition" >

attachment;filename="${downloadFileName}"

</ param >

         < param name = "bufferSize" > 5120 </ param >

    </ result >

</ action >

2 action

public class HxrBaseInfoAction

………………

// 导出下载使用

    private String fileName ;  // 下载文件名

    private InputStream inputStream ;  // 下载文件使用流

    /**

      * 下载方法

      * @return

      * @throws Exception

      */

    public String exportZip() throws Exception {

       return "down" ;

       //1 、调用 getInputStream()  Stream 中给文件

       //2 、调用 getDownloadFileName 取得下载名 解决了中文乱码

       // 如果是前台传过来的中文乱码,还要在

    }

    public InputStream getInputStream() {

       try {

           this .setFileName( 可以给定“中文名” );

           this . inputStream = new FileInputStream( this . fileName );

       } catch (FileNotFoundException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

       return this . inputStream ;

    }

 

    public void setInputStream(InputStream inputStream) ………………

    /**

      * 指定下载文件名称   解决了中文乱码   可见配置文件中对应 ${downloadFileName}

      * @return

      */

    public String getDownloadFileName(){

       String fn = "" ;

       try {

           String temp = this .getFileName(). ……………… ;

           fn = new String(temp.getBytes(), "ISO8859-1" );

       } catch (UnsupportedEncodingException e) {

           e.printStackTrace();

       }

       return fn;

    }

    解决传参是“中文”时的乱码。为里对应下面 js 请求下载

public void setFileName(String fileName) {

       try {

           this . fileName = URLDecoder.decode (fileName, "utf-8" );

       } catch (UnsupportedEncodingException e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

    }

Js  get 传值 》乱码解决方法

var url = $.url.encode(" 候选人授权书 - 太和鼎信 ") ;  // 解决中文件名乱码

window.open("downloadOrUpload_down.action?fileName="+$.url.encode(url)+".pdf","_self");

 

 

 

 二、上传

1、action

     //文件上传
    private File uploadFile;//得到上传的文件
    private String uploadFileContentType;//得到文件的类型
    private String uploadFileFileName;//得到文件的名称

 

getter setter 省略

 

/***
     * 接收上传文件
     * @return
     * @throws Exception
     */
    public String upload() throws Exception {
        try {
            //String realpath = ServletActionContext.getServletContext().getRealPath("/downloadFiles/upload");
            String realpath = (String) Constant.getValue("hxr.baseInfo.upFiles");
            File file = new File(realpath);
            if(!file.exists()) file.mkdirs();
            //取得扩展名
            String fileExtName = uploadFileFileName.substring(uploadFileFileName.indexOf(".")+1);
            //生成新的文件名
            String newFileName = UUID.randomUUID().toString()+"."+fileExtName;
            FileUtils.copyFile(uploadFile, new File(file, newFileName));
            //生成缩略图   支持生成//bmp,jpg,rar,doc,pdf,zip,tif
            String filterStr = "bmp,jpg,tif";
            String littleImgRelePath = ServletActionContext.getServletContext().getRealPath("/downloadFiles/littleImg");
            String littleImgPath = "";  //小图路径
            if(filterStr.indexOf(fileExtName)>-1) {
                // TODO 调用  高立收  方法生成  小图
                ScaleImage.saveImageAsJpg(realpath+newFileName, littleImgRelePath+"/"+newFileName, 440, 400);
                //ScaleImage.saveImageAsJpg(realpath+"lilteImage/",);
                littleImgPath = "downloadFiles/littleImg/"+ newFileName;
            }
            // session中注册 文件
            Map<String, Boolean> fileMap = (Map<String, Boolean>) this.getRequest().getSession().getAttribute("fliesMap");
            fileMap.put(realpath+newFileName, false); //原图注册
            fileMap.put(littleImgRelePath+"/"+newFileName, false);  //缩略图注册
            if(!"".equals(littleImgPath)) fileMap.put(littleImgPath, false);
            this.returnString("{success:true,filePath:'"+realpath+newFileName+"',fileName:'"+uploadFileFileName+"',littleImgPath:'"+littleImgPath+"'}", "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            this.returnString("{success:false}", "UTF-8");
        }
          return null;
    }

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics