struts2上传文件

自己写了一个工具类 方便获取上传文件的相关数据

public class FileUploadUtil {

    /**
     * 获取上传文件的扩展名
     */
    private static String getFileExt(String fileName){
        return FilenameUtils.getExtension(fileName);
    }

    /**
     * 用uuid随机生成名字,加上扩展名返回文件新名字 
     */
    private static String newFileName(String fileName){
        String ext = getFileExt(fileName);
        return UUID.randomUUID().toString() + "." + ext;
    }

    /**
     * 从配置文件中获取要上传的文件路径
     */
    public static String getPath(String uploadType){
        // 配置文件在src下获取配置文件路径
        InputStream path = FileUploadUtil.class.getClassLoader().getResourceAsStream("sys.properties");
        Properties prop = new Properties();
        try {
            prop.load(path);
            System.out.println(prop.getProperty("ImgUrl"));
        } catch(IOException e) {
            e.printStackTrace();
        }
        return prop.getProperty(uploadType);
    }

    /**
     * 获取与服务器同级的上传文件路径
     */
    public static String getUploadFilePath(String uploadType){
        HttpServletResponse response = ServletActionContext.getResponse();
        HttpServletRequest request = ServletActionContext.getRequest();
        response.setCharacterEncoding("utf-8");

        String path = request.getSession().getServletContext().getRealPath("");       // 项目路径

        path = path.substring(0,path.lastIndexOf(File.separator));                    // 项目上一级路径

        String url ="/"+getPath(uploadType);                      

        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        url += df.format(date);// 文件夹--日期
        url += "/";

        return path+url;
    }

    /**
     * 实现文件上传的功能,返回上传后新的文件路径  
     */
    /*public static String uploadFile(UploadFile fileImage , String uploadType){
        String filePath = getUploadFilePath(uploadType);

        File f2 = new File(filePath);
        if (!f2.exists()) {
            f2.mkdirs();
        }

        File file = null;
        String picNewName = "";

        do {
            //获取文件新名字
            picNewName = newFileName(fileImage.getFileName());
            file = new File( filePath + picNewName);
        } while (file.exists());

        try {
            FileUtil.copyFile(fileImage.getFile(), file);
            //第一个参数是上传的文件,第二个参数是将文件拷贝
            return filePath + picNewName;
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        } finally {  
            fileImage.getFile().delete();  
        } 
    }*/
}

Parameters 类从struts上传的文件中取得fileFileName,fileContentType,file三个参数,放入map集合中

public class Parameters {
    /**
     * 获取参数  struts2特有的属性的fileFileName fileContentType file
     * 
     * @param fileFileName
     *            文件名称
     * @param fileContentType
     *            文件类型
     * @param file
     *            上传的文件
     */
    public static Map<String, Object> getUploadParameters() {
        Map<String, Object> m = new HashMap<String, Object>();
        ActionContext context = ActionContext.getContext();
        Set set = context.getParameters().keySet();
        Iterator ite = set.iterator();
        while (ite.hasNext()) {
            Object men = ite.next();
            Object[] param = (Object[]) context.getParameters().get(
                    men.toString());
            if (param.length > 1) {
                String para = "";
                for (int i = 0; i < param.length; i++) {
                    if (i == param.length - 1) {
                        para += param[i];
                    } else {
                        para += param[i] + ",";
                    }
                }
                m.put(men.toString(), para);
            } else {
                m.put(men.toString(), param[0]);
            }
        }
        return m;
    }
}

fileUpload方法将文件上传,返回存放路径

    public String fileUpload(){
        String path = FileUploadUtil.getUploadFilePath("sys.properties下的某一参数");
        //用FileUploadUtil 类中的getUploadFilePath方法是为了获取要上传到某一位置的路径

        File f2 = new File(path);
        if (!f2.exists()) {
            f2.mkdirs();
        }

        Map<String, Object> map = Parameters.getUploadParameters();
        File f = (File) map.get("file");
        String fileName = (String) map.get("fileFileName");

        if(fileName!=null && !fileName.equals("")){
            File file  = new File( path + fileName);

            CopyFileUtil.copyFile(f.getPath(),file.getPath(), true);

            f.delete();

            return path + fileName; 
        }else{
            return "";
        }
    }

在上传文件时,有些文件会为null 可能是因为文件大小超过struts的默认大小,修改strhts2的配置即可

<!-- 修改系统上传文件大小  默认5M -->
    <constant name="struts.multipart.maxSize" value="1073741824"/>  
    <!-- 1G=1024*1024*1024 -->

<action name="UploadFile" class="com.buptisc.srpms.action.UploadFileAction">
    <interceptor-ref name="fileUpload">
        <!-- 修改上传文件大小  默认2M -->
        <param name="maximumSize">1070000000</param> 
    </interceptor-ref>
</action>

在这里maximumSize需要小于struts.multipart.maxSize

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值