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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值