Struts2文件上传与下载(中文名称的文件正常上传与下载)

项目的层次结构:

index.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>My JSP '1.jsp' starting page</title>  
      </head>  
        
     <h3>Struts2文件上传示例</h3><hr/>  
    <s:fielderror/>  
    <form action="upload.action" method="post" enctype="multipart/form-data"><!-- 此处必须为multipart/form-data,而且必须使用post方法 -->  
        <table border="1" width="500">  
            <tr>  
                <td>选择文件</td>  
                <td><input type="file" name="upload" /></td>  
            </tr>  
            <tr>  
                <td colspan="2" align="center"><input type="submit" value='提交' /></td>  
            </tr>  
        </table>  
        
   		 <a href="download.action?fileName=Eclipse4张三.doc">下载.jpg</a><br/>  
    </form>  
  </body>   
    </html>  

web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
        xmlns="http://java.sun.com/xml/ns/javaee"  
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  
        id="WebApp_ID" version="3.0">  
        <display-name>uploadTest</display-name>  
       
       <filter>
  	<filter-name>struts2</filter-name>
	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  </filter>
  
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
        <welcome-file-list>  
            <welcome-file>index.jsp</welcome-file>  
        </welcome-file-list>  
      
</web-app>  

上传Action

package com.imut.action;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {  
	 /** 代表上传的文件内容的对象 */  
    private File upload;  
      
    /** Struts2约定的代表上传的文件的名 */  
    private String uploadFileName;  
    /** Struts2约定的代表上传文件的内容类型(MIME) */  
    private String uploadContentType;  
      
    public String execute() throws Exception{  
        System.out.println("文件的名:" + uploadFileName);  
        System.out.println("不要用upload.getName()来获取文件名,这个是临时名:" + upload.getName());  
        System.out.println("文件的内容类型:" + uploadContentType);  
          
        //使用IO流来操作upload属性  
        //File destPath = new File("d:/"); //服务端存放文件的目录  
          
        //如果要存放到web服务器中本项目的某个目录下  
        //根据服务器的文件保存地址和原文件名创建目录文件全路径  
        String destPath = ServletActionContext.getServletContext().getRealPath("/upload");  
          
        File dest = new File(destPath, uploadFileName); //服务器的文件  
          
        FileUtils.copyFile(upload, dest);//完成了文件的拷贝工作  
          
        return "success";  
    }  
      
     
    public File getUpload() {  
        return upload;  
    }  
    public void setUpload(File upload) {  
        this.upload = upload;  
    }  
    public String getUploadFileName() {  
        return uploadFileName;  
    }  
    public void setUploadFileName(String uploadFileName) {  
        this.uploadFileName = uploadFileName;  
    }  
    public String getUploadContentType() {  
        return uploadContentType;  
    }  
    public void setUploadContentType(String uploadContentType) {  
        this.uploadContentType = uploadContentType;  
    }  
  
}  

下载Action

package com.imut.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;

import com.opensymphony.xwork2.ActionSupport;

public class DownLoadAction extends ActionSupport {  
	 private String basePath = ServletActionContext.getServletContext().getRealPath("/upload");  
	   private String fileName;  
	      
	      
	    public String execute(){  
	        return "success";  
	    }  
	      
	    public InputStream getInputStream() throws FileNotFoundException{  
	    	System.out.println(fileName);
	    	
	    	System.out.println(basePath);
	    	String fileName=ServletActionContext.getRequest().getParameter("fileName");
	    	  String downFileName = fileName;
	    	  try {
				downFileName = new String(downFileName.getBytes("ISO8859-1"), "utf-8");
				System.out.println(downFileName+"***");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
	        return new FileInputStream(new File(basePath, downFileName));  
	    }  
	  
	    public String getFileName() throws UnsupportedEncodingException {  
	    	  String fileName=ServletActionContext.getRequest().getParameter("fileName");
	    	  String downFileName = fileName;
	    	  downFileName = new String(downFileName.getBytes("ISO8859-1"), "ISO8859-1");
	    	  return new String(downFileName);  
	    }  
	  
	    public void setFileName(String fileName) {  
	        this.fileName = fileName;  
	    }  
}  

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>  
    <!DOCTYPE struts PUBLIC  
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
        "http://struts.apache.org/dtds/struts-2.0.dtd">  
      
    <struts>  
        <constant name="struts.devMode" value="true" />  
        <constant name="struts.custom.i18n.resources" value="message"></constant>  
        <package name="default" namespace="/"  extends="struts-default">  
           <action name="upload" class="com.imut.action.UploadAction">  
            <!-- 可以更改fileUpload拦截器的属性值来限定上传文件的内容类型,上传文件的大小 -->  
            <interceptor-ref name="defaultStack">  
      <param name="fileUpload.allowedTypes">image/png,image/gif,image/jpeg,image/jpg,image/x-png, image/pjpeg,text/plain,application/msword</param> 
         <param name="fileUpload.allowedExtensions">  
			    png,bmp,jpg,doc,xls,txt
			</param> 
      <param name="fileUpload.maximumSize">20971520</param> 
        </interceptor-ref>              
            <result name="success">/success.jsp</result>  
            <result name="input">/index.jsp</result>  
        </action>
            
            
			
			<action name="download" class="com.imut.action.DownLoadAction">  
            <result name="success" type="stream">  
                <param name="contentType">application/octet-stream;charset=ISO8859-1</param>  
                <param name="inputName">inputStream</param>  
                <param name="contentDisposition">attachment;filename=${fileName}</param>  
              <!--  <param name="bufferSize">8192</param>  -->
            </result>  
        </action>
        </package>  
    </struts>  


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值