Struts2.0 文件上传与下载全解析

struts的上传封装的已经非常完美了,首先我们来看一下页面



    <s:form action="saveDocument.action" method="post" enctype ="multipart/form-data">

                            <td height="32" class="heder">
                                上传档案 :
                            </td>               
                            <td align="left" bgcolor="#FFFFFF" class="main2">
                                <s:file name="documentFile" />
                            </td>

                            <td align="center">
                                <input type="submit" value="保  存" class="button" onclick="return nextsubmit();"/>
                            </td>

    </s:form>
主要关注的就是 <s:file name="documentFile" />    enctype ="multipart/form-data"


在action中,我们来看


    private String documentFileContentType;
    private String documentFileFileName;
    private File documentFile;

    public String getDocumentFileContentType() ...{
        return documentFileContentType;
    }

    public void setDocumentFileContentType(String documentFileContentType) ...{
        this.documentFileContentType = documentFileContentType;
    }

    public String getDocumentFileFileName() ...{
        return documentFileFileName;
    }

    public void setDocumentFileFileName(String documentFileFileName) ...{
        this.documentFileFileName = documentFileFileName;
    }

    public File getDocumentFile() ...{
        return documentFile;
    }

    public void setDocumentFile(File documentFile) ...{
        this.documentFile = documentFile;
    }

    private void copy(File src, File dst) ...{    
        InputStream in = null;
        OutputStream out = null;
        try...{               
            in = new BufferedInputStream( new FileInputStream(src));
            out = new BufferedOutputStream( new FileOutputStream(dst));
           
            byte [] buffer = new byte [1024];   
            while (in.read(buffer) > 0 )   
                out.write(buffer);     
            in.close();
            out.close();
        }catch (Exception e) ...{   
            e.printStackTrace();   
        }    
           
    }


    public String save()...{

        if(!documentFileFileName.equals(""))...{
           
       
            String folder = ServletActionContext.getServletContext()
                                .getRealPath("/archives");
           
            File rootDir = new File(folder);
           
            if(!rootDir.exists())
                rootDir.mkdirs();
           
            String fileEx = documentFileFileName.substring(
                                documentFileFileName.indexOf("."),
                                documentFileFileName.length());
           
            String fileRealName = documentFileFileName.substring(0, documentFileFileName.indexOf(".")) + String.valueOf(new Date().getTime())+fileEx;
           
            String fileName = folder + "\" + fileRealName;
   
           
            copy(documentFile,new File(fileName));
           

        }
               

           
        return "success";
    }
documentFileContentType;   documentFileFileName;  documentFile;  上传后这三个东西会自动注入进来,根据要求对文件名更改下,保存下

好了,接着我们要提供下载,看看struts是怎么做的,网上关于这方面资料很少,就一个家伙把官方的showcase翻译下,我再完整的走一遍流程

在页面中


<s:url id="url" action="download"> <s:param name="inputPath">/archives/<s:property value="loc" /></s:param>
</s:url>
<s:a href="%{url}">下载</s:a>
在action中


import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;



public class FileDownloadAction implements Action ...{

   
    private String inputPath;
    public void setInputPath(String value) throws UnsupportedEncodingException ...{
        inputPath =  new String(value.getBytes("ISO-8859-1"),"UTF-8");
        System.out.println();
    }

    public InputStream getInputStream() throws Exception ...{
        return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
    }

    public String execute() throws Exception ...{
        String fileName = inputPath.substring(inputPath.lastIndexOf("/")+1, inputPath.length());
        ServletActionContext.getResponse().setHeader("Content-Disposition", "attachment; filename="+new String(fileName.getBytes("gb2312"),"iso-8859-1"));

        return SUCCESS;
    }

   
   

}
相应的XML配置


        <action name="download" class="FileDownloadAction">
            <result name="success" type="stream">
                <param name="inputName">inputStream</param>
                <param name="bufferSize">4096</param>
            </result>
        </action>
这里要注意,在action中 inputPath =  new String(value.getBytes("ISO-8859-1"),"UTF-8");  需要转换下
另外在setHeader("Content-Disposition", "attachment; filename="+new String(fileName.getBytes("gb2312"),"iso-8859-1"));
这一步也是非常重要的。
注意:第一个转换,"ISO-8859-1"————"UTF-8"  UTF-8是根据你自己的编码来处理
第二个转换,"gb2312"————"iso-8859-1"  你就不要改变了,不管你是什么编码,都这么处理就是了,只要你的客户用的是中文的操作系统,呵呵


大家在官方例子showcase里看到的是这样的



        <action name="download" class="org.apache.struts2.showcase.filedownload.FileDownloadAction">
            <param name="inputPath">/images/struts.gif</param>
            <result name="success" type="stream">
                <param name="contentType">image/gif</param>
                <param name="inputName">inputStream</param>
                <param name="contentDisposition">filename="struts.gif"</param>
                <param name="bufferSize">4096</param>
            </result>
        </action>
可以看到 inputPath 我们已经写在了jsp的URL中了,contentType 这个东西也是大家比较恼火的,因为对于图片、zip、rar、doc、word、txt都是不同的,我这里做了个实验,干脆不要了,让系统自己去判断,发现可行,呵呵,可能struts会自动判断,contentDisposition 我们也写在action的response中了,剩下的2个inputname和bufferSize就让它放着吧,反正不用改变,好了,经过上述的改变,终于符合业务需求了,呵呵

你可能感兴趣的:(java,jsp,struts,post,action)