struts2框架(三)文件上传与下载

通过struts-default.xml里面的fileUpload拦截器实现文件上传与下载。

1.FileUploadInterceptor里面的相关方法

 /**
     * Sets the allowed extensions
     * 限制运行的文件的扩展名
     * @param allowedExtensions A comma-delimited list of extensions
     */
    public void setAllowedExtensions(String allowedExtensions) {
        allowedExtensionsSet = TextParseUtil.commaDelimitedStringToSet(allowedExtensions);
    }

    /**
     * Sets the allowed mimetypes
     * 设置允许的mimetype
     * @param allowedTypes A comma-delimited list of types
     */
    public void setAllowedTypes(String allowedTypes) {
        allowedTypesSet = TextParseUtil.commaDelimitedStringToSet(allowedTypes);
    }

    /**
     * Sets the maximum size of an uploaded file
     * 设置上传的最大文件大小
     * @param maximumSize The maximum size in bytes
     */
    public void setMaximumSize(Long maximumSize) {
        this.maximumSize = maximumSize;
    }

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
     */

    public String intercept(ActionInvocation invocation) throws Exception {
        ActionContext ac = invocation.getInvocationContext();

        HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);

        if (!(request instanceof MultiPartRequestWrapper)) {
            if (LOG.isDebugEnabled()) {
                ActionProxy proxy = invocation.getProxy();
                LOG.debug(getTextMessage("struts.messages.bypass.request", new Object[]{proxy.getNamespace(), proxy.getActionName()}, ac.getLocale()));
            }

            return invocation.invoke();
        }

        ValidationAware validation = null;

        Object action = invocation.getAction();

        if (action instanceof ValidationAware) {
            validation = (ValidationAware) action;
        }

        MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;

        if (multiWrapper.hasErrors()) {
            for (String error : multiWrapper.getErrors()) {
                if (validation != null) {
                    validation.addActionError(error);
                }

                if (LOG.isWarnEnabled()) {
                    LOG.warn(error);
                }
            }
        }

        // bind allowed Files
        Enumeration fileParameterNames = multiWrapper.getFileParameterNames();
        while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {
            // get the value of this input tag
           // 获取标签名file1
            String inputName = (String) fileParameterNames.nextElement();

            // get the content type
            String[] contentType = multiWrapper.getContentTypes(inputName);

            if (isNonEmpty(contentType)) {
                // get the name of the file from the input tag
                String[] fileName = multiWrapper.getFileNames(inputName);

                if (isNonEmpty(fileName)) {
                    // get a File object for the uploaded File
                    File[] files = multiWrapper.getFiles(inputName);
                    if (files != null && files.length > 0) {
                        List acceptedFiles = new ArrayList(files.length);
                        List acceptedContentTypes = new ArrayList(files.length);
                        List acceptedFileNames = new ArrayList(files.length);
                        String contentTypeName = inputName + "ContentType";
                        String fileNameName = inputName + "FileName";

                        for (int index = 0; index < files.length; index++) {
                            if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation, ac.getLocale())) {
                                acceptedFiles.add(files[index]);
                                acceptedContentTypes.add(contentType[index]);
                                acceptedFileNames.add(fileName[index]);
                            }
                        }

                        if (!acceptedFiles.isEmpty()) {
                            Map params = ac.getParameters();

                            params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()]));
                            params.put(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()]));
                            params.put(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()]));
                        }
                    }
                } else {
                    if (LOG.isWarnEnabled()) {
                    LOG.warn(getTextMessage(action, "struts.messages.invalid.file", new Object[]{inputName}, ac.getLocale()));
                    }
                }
            } else {
                if (LOG.isWarnEnabled()) {
                    LOG.warn(getTextMessage(action, "struts.messages.invalid.content.type", new Object[]{inputName}, ac.getLocale()));
                }
            }
        }

        // invoke action
        return invocation.invoke();
    }

2.文件上传与下载实例

FileUpload:文件上传Action

import java.io.File;

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

import com.opensymphony.xwork2.ActionSupport;

public class FileUpload extends ActionSupport {

    // 对应表单:
    private File file1;
    // 文件名
    private String file1FileName;
    // 文件的类型(MIME)
    private String file1ContentType;

    public void setFile1(File file1) {
        this.file1 = file1;
    }

    public void setFile1FileName(String file1FileName) {
        this.file1FileName = file1FileName;
    }

    public void setFile1ContentType(String file1ContentType) {
        this.file1ContentType = file1ContentType;
    }

    @Override
    public String execute() throws Exception {
        /****** 拿到上传的文件,进行处理 ******/
        // 把文件上传到upload目录

        // 获取上传的目录路径
        String path = ServletActionContext.getServletContext().getRealPath(
                "/upload");
        // 创建目标文件对象
        File destFile = new File(path, file1FileName);
        // 把上传的文件,拷贝到目标文件中
        FileUtils.copyFile(file1, destFile);

        return SUCCESS;
    }
}

DownAction:文件列表展示和下载Action

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DownAction extends ActionSupport {
    
    
    /*************1. 显示所有要下载文件的列表*********************/
    public String list() throws Exception {
        
        //得到upload目录路径
        String path = ServletActionContext.getServletContext().getRealPath("/upload");
        // 目录对象
        File file  = new File(path);
        // 得到所有要下载的文件的文件名
        String[] fileNames =  file.list();
        // 保存
        ActionContext ac = ActionContext.getContext();
        // 得到代表request的map (第二种方式)
        Map request= (Map) ac.get("request");
        request.put("fileNames", fileNames);
        return "list";
    }
    
    
    /*************2. 文件下载*********************/
    
    // 1. 获取要下载的文件的文件名
    private String fileName;
    public void setFileName(String fileName) {
        // 处理传入的参数中问题(get提交)
        try {
            fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        // 把处理好的文件名,赋值
        this.fileName = fileName;
    }
    
    //2. 下载提交的业务方法 (在struts.xml中配置返回stream)
    public String down() throws Exception {
        return "download";
    }
    
    // 3. 返回文件流的方法
    public InputStream getAttrInputStream(){
        return ServletActionContext.getServletContext().getResourceAsStream("/upload/" + fileName);
    }
    
    // 4. 下载显示的文件名(浏览器显示的文件名)
    public String getDownFileName() {
        // 需要进行中文编码
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return fileName;
    }

    
}

配置文件:






    
        
        
        
            
            
                
                
                txt,jpg,jar
                
                
                
            
            
            /e/success.jsp
            
            
            /e/error.jsp
        
        
        
            
            /e/list.jsp
            
            
            
                
               application/octet-stream
               
               
               attrInputStream
               
               
               attachment;filename=${downFileName}
             
                
               1024
            
        
      

上传页面表单:

用户名:
<%--name的取名file1要和上传Action里面的字段对应--%> 文件:

文件列表和下载页面:


        <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
        
            
编号 文件名 操作
${vs.count } ${fileName } 下载

你可能感兴趣的:(struts2框架(三)文件上传与下载)