Struts2.0多文件上傳下載

一、文件上傳
Struts2並沒有提供文件上傳的組件,所以想要實現上傳的功能就必須通過第三方組件來實現,在Struts2引用的jar中包含了文件上傳的組件,它是通過commons-fileupload.jar和commons-io.jar來實現的。這其中的處理細節不需要太懂,在使用中慢慢思考就可以做到靈活運用。

1、編寫Action類
文件上傳的核心實現使用的還是java的數據流io操作,上傳文件時要防止文件上傳重複覆蓋,

文件上傳操作類:

public String setFile(List<File> fileList,List<String> fileListFileName,List<String> fileListContentType) throws IOException{
        String root = ServletActionContext.getServletContext().getRealPath("/upload/sample")+File.separator;//+tmpPath+File.separator;
        System.out.println("root=="+root);
        File f = new File(root);
        if(!f.exists()){
            f.mkdirs();
        }
        File[] files = FileUtil.listSortedFiles(f);
        String path="";
        for(int i = 0; i < fileList.size(); i++)
        {
            InputStream is = new FileInputStream(fileList.get(i));

            String filename = fileListFileName.get(i);  
            String fileName1 = filename.substring(0,filename.lastIndexOf("."));
            String fileSuffix1 = filename.substring(filename.lastIndexOf("."));
            Integer fileIndex = -1;
            for (File file : files) {
                if(file.isDirectory())continue;
                String fileName = file.getName();
                String fileSuffix = "";
                if(file.getName().lastIndexOf(".") > -1){
                    fileName = file.getName().substring(0,file.getName().lastIndexOf("."));
                    fileSuffix = file.getName().substring(file.getName().lastIndexOf("."));
                }
                if(fileName.indexOf(fileName1)==0 && fileSuffix.equals(fileSuffix1)){
                    if(fileName.equals(fileName1)){
                        if(fileIndex == -1){
                            filename = fileName + "-副本" + fileSuffix;
                            fileIndex = 0;
                        }
                    }else if(fileName.indexOf("-副本")>0){
                        int index = fileName.indexOf("-副本");
                        String num = "".equals(fileName.substring(index+3))?"0":fileName.substring(index+3);
                        Integer tmp = (Integer.parseInt(num)+1);
                        if(fileIndex < tmp){
                            fileIndex = tmp;
                            filename = fileName1 + "-副本" + tmp + fileSuffix;
                        }
                    }
                }
            }
            OutputStream os = new FileOutputStream(new File(root, filename));//
            path += ("".equals(path)?"":";")+root+filename;
            byte[] buffer = new byte[500];

            @SuppressWarnings("unused")
            int length = 0;

            while(-1 != (length = is.read(buffer, 0, buffer.length)))
            {
                os.write(buffer);
            }

            os.close();
            is.close();
        }
        return path;
    }

action調用類:

private List<File> cerFiles;
    private List<String> cerFilesFileName;
    private List<String> cerFilesContentType;
public String save() throws IOException{
        String path1=this.setFile(cerFiles, cerFilesFileName, cerFilesContentType);
        sampleCertificationInfo.setAttachmentCerPath(path1);
 }

jsp頁面:

<script type="text/javascript">

$(function()
{
    $("#button1").click(function()
    {
        var html = $("<input type='file' name='cerFiles'>");
        var button = $("<input type='button' name='button' value='刪除'><br>");

        $("#add1").append(html).append(button);

        button.click(function()
        {
            html.remove();
            button.remove();
        })
    })
})
   </script>
<form action="sampleCertificationAction_save.action" method="post" enctype="multipart/form-data">
<input type="file" name="cerFiles">
                    <input type="button" value="添加" id="button1"><br>
                    <div id="add1"></div>
  </form>

一、文件下載
Action代碼:

 private String fileName;
  private InputStream fileInput; 
public InputStream getDownloadFile()
    {
        return ServletActionContext.getServletContext().getResourceAsStream("upload\\sample\\"+fileName);
    }
    public String getFileDown(){
        System.out.println("下載的文件是==="+fileName);
        fileInput=ServletActionContext.getServletContext().getResourceAsStream("upload\\sample\\"+fileName);
        try {
            fileName = new String(fileName.getBytes(), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if(fileInput ==  null){
            return  "";
        }
        System.out.println("fileInput=="+fileInput);
        return "success";
    }
    public InputStream getFileInput() {
        return fileInput;
    }
    public void setFileInput(InputStream fileInput) {
        this.fileInput = fileInput;
    }

jsp頁面:顯示文件名
Map

<s:iterator value="#filenamesList" id="val">
                     <a href="sampleBaseInfoAction_getFileDown.action?fileName=<s:property value="#val"/>" target="tmp_upload_iframe"><s:property value="#val"/></a></br>
                </s:iterator>
                如果直接是List<String>集合存儲文件名,jsp顯示用以下方式:
<s:iterator value="#infoList" id="val">
                     <a href="sampleBaseInfoAction_getFileDown.action?fileName=<s:property value="#val"/>" target="tmp_upload_iframe"><s:property value="#val"/></a></br>
                </s:iterator></td>

下載最主要的是struts-xml文件的配置:

<result name="success" type="stream"> 
            <param name="contentType">application/octet-stream</param> 
        <param name="inputName">fileInput</param>  
<param name="contentDisposition">attachment;filename="${fileName}"</param>           
        <param name="bufferSize">4096</param> 
        </result>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章