struts文件上传

Struts2 文件上传

struts文件上传,获取文件名和文件类型
/**
Action中还有两个属性:uploadFileName和uploadContentType,这两个属性分别用于封装上传文件的文件名、文件类型。这是Struts2设计的独到之处:Strut2的Action类直接通过File类型属性直接封装了上传文件的文件内容,但这个File属性无法获取上传文件的文件名和文件类型,所以Struts2就直接将文件域中包含的上传文件名和文件类型的信息封装到uploadFileName和 uploadContentType属性中,也就是说Struts2针对表单中名为xxx的文件域,在对应的Action类中使用3个属性来封装该文件域信息:
l 类型为File的xxx属性:用来封装页面文件域对应的文件内容。
l 类型为String的xxxFileName属性:用来封装该文件域对应的文件的文件名。
l 类型为String的xxxContentType属性:用来封装该文件域应用的文件的文件类型。
**/


package com.huawei.lifeservice.home.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionContext;

public class FileUploadAction extends BaseAction
{
    private static final long serialVersionUID = 4668957692981296279L;
    
    private static Logger logger = LoggerFactory.getLogger(FileUploadAction.class);
    
    /**
     * 图片文件
     */
    private static final String FILE_DOT = ".";
    
    /**
     * 上传文件存放路径
     */
    private final static String UPLOADDIR = "/upload";
    
    /**
     * 文件类型对应的存储位置
     */
    private static final Map<String, String> map = new HashMap<String, String>();
    
    static
    {
        map.put("image/png", "pic");
        map.put("image/jpeg", "pic");
        map.put("image/gif", "pic");
        map.put("text/html", "page");
    }
    
    /**
     * 上传文件集合
     */
    private List<File> file;
    
    /**
     * 上传文件名集合
     */
    private List<String> fileFileName;
    
    /**
     * 上传文件内容类型集合
     */
    private List<String> fileContentType;
    
    public List<File> getFile()
    {
        return file;
    }
    
    public void setFile(List<File> file)
    {
        this.file = file;
    }
    
    public List<String> getFileFileName()
    {
        return fileFileName;
    }
    
    public void setFileFileName(List<String> fileFileName)
    {
        this.fileFileName = fileFileName;
    }
    
    public List<String> getFileContentType()
    {
        return fileContentType;
    }
    
    public void setFileContentType(List<String> fileContentType)
    {
        this.fileContentType = fileContentType;
    }
    
    public String execute()
    {
        return "success";
    }
    
    public void process()
    {
        String imageUrl = null;
        for (int i = 0; i < file.size(); i++)
        {
            imageUrl = uploadFile(i);
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("url", imageUrl);
        ClientWriter.write2Client(response, map);
    }
    
    public String generateFileName(String fileType)
    {
        String fileName = UUID.randomUUID().toString();
        fileName = fileName.replaceAll("-", "");
        
        if (map.containsKey(fileType))
        {
            // map.get(fileType);
            fileType = fileType.substring(fileType.lastIndexOf("/"));
            fileType = fileType.replaceAll("\\/", FILE_DOT);
        }
        else
        {
            logger.info("file type no exists...");
            fileType = FILE_DOT + "unknown";
        }
        
        return fileName += fileType;
    }
    
    @SuppressWarnings("deprecation")
    public String getSavePath(String fileType)
    {
        String dir = ServletActionContext.getRequest().getRealPath(UPLOADDIR);
        logger.info("file save dir is " + dir);
        
        String path = File.separator;
        if (map.containsKey(fileType))
        {
            path += map.get(fileType) + File.separator;
        }
        
        return dir + path;
    }
    
    private String uploadFile(int i)
    {
        String fileName = null;
        String savePath = null;
        String fileContentType = null;
        
        try
        {
            InputStream in = new FileInputStream(file.get(i));
            
            fileContentType = this.getFileContentType().get(i);
            logger.info("file content type is " + fileContentType);
            
            fileName = generateFileName(fileContentType);
            savePath = getSavePath(fileContentType);
            
            File uploadFile = new File(savePath + fileName);
            OutputStream out = new FileOutputStream(uploadFile);
            
            byte[] buffer = new byte[1024 * 1024];
            int length = 0;
            while ((length = in.read(buffer)) > 0)
            {
                out.write(buffer, 0, length);
            }
            
            in.close();
            out.close();
        }
        catch (FileNotFoundException e)
        {
            logger.error("file not found error", e);
        }
        catch (IOException e)
        {
            logger.error("io error", e);
        }
        
        String accessUrl = getAccessUrl(fileContentType) + fileName;
        return accessUrl;
    }
    
    public void getWebRootPath()
    {
        ActionContext context = ActionContext.getContext();
        ServletContext sc = (ServletContext)context.get(ServletActionContext.SERVLET_CONTEXT);
        String contextPath = sc.getContextPath();
        
        logger.info("contextPath is" + contextPath);
        
        ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT);
        
        String temp = ServletActionContext.getServletContext().getContextPath();
        System.err.println(temp);
        
        SimpleResp<Object> simple = new SimpleResp<Object>();
        simple.setData("ok");
        simple.setResult(new Result(ReturnCode.PARAM_EPT));
        
        ClientWriter.write2Client(response, simple);
    }
    
    public String getWebApplicationRoot()
    {
        ActionContext ac = ActionContext.getContext();
        ServletContext sc = (ServletContext)ac.get(ServletActionContext.SERVLET_CONTEXT);
        String contextPath = sc.getContextPath();
        return contextPath;
    }
    
    public String getAccessUrl(String fileType)
    {
        String webRoot = getWebApplicationRoot();
        String path = File.separator;
        if (map.containsKey(fileType))
        {
            path += map.get(fileType);
        }
        
        String accessUrl = webRoot + UPLOADDIR + path + File.separator;
        accessUrl = accessUrl.replaceAll("\\\\", "/");
        return accessUrl;
    }
}

你可能感兴趣的:(struts)