Java_文件上传与下载(三)

Struts2实现


1.原理

a.表单中设置为post提交,encytype属性设置为multipart/form-dat,这样数据就以二进制流的方式传输
b.Struts2默认采用Jakarta和Common-FileUpload框架,导入相应jar包即可
c.通过Struts2的拦截器设置上传文件的类型及大小等
d.在Struts2的action中设置上传文件的内容、类型及名称 

2.文件上传

(1)Action的写法:

public class FileUploadAction extends ActionSupport {

    private File upload;    //这里必须与表单中的input的Name一致
    private String uploadContentType;
    private String uploadFileName;

    private String result;

    //省略set/get方法
    。。。。。。
    。。。。。。

    //Struts2的action中excute方法的覆写
    @Override
    public String execute() throws Exception {

        String filePath = ServletActionContext.getServletContext().getRealPath("/images");
        File file = new File(filePath);
        if(!file.exists()){
            file.mkdir();
        }
        FileUtils.copyFile(upload, new File(file,uploadFileName));
        result = "上传成功!";

        return SUCCESS;
    }
}

(2)Struts2的xml配置:*


    
        /jsps/struts2upload.jsp
        /jsps/error.jsp
        
        
              
            image/jpeg,image/gif,image/png
            
            10M
        

                     
    

(3)异常处理:

引入struts2的国际化的支持,在xml中添加
    
资源文件:假设定义了resouce_zh_CN.properties的文件

(4)批量上传:

a.jsp中多加几个input

    上传文件1:
上传文件2:
上传文件3:
b.Action中的成员定义为List private List upload; private List uploadContentType; private List uploadFileName; c.保存文件时循环逐个保存

(2)文件下载

(1)Struts2的xml配置:

      
    
        /images/image2.jpg
        
            application/octet-stream
            inputStream
            attachment;filename="${downloadFileName}"
            8192
        
       

(2)Action的写法:

private String inputPath;
public String filename;

public String getInputPath() {
    return inputPath;
}

public void setInputPath(String inputPath) {
    this.inputPath = inputPath;
}

@Override
public String execute() throws Exception {

    return SUCCESS;
}


public InputStream getInputStream() throws IOException{

    String path =  ServletActionContext.getServletContext().getRealPath("/images");
    String filePath = path+"\\"+ filename;
    File file = new File(filePath);
    return FileUtils.openInputStream(file);
    //return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
}

public String getDownloadFileName(){
    String downloadFileName = "";
    try {
        downloadFileName=URLEncoder.encode("下载文件.jpg","UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return downloadFileName;
}

你可能感兴趣的:(JAVA)