码迷,mamicode.com
首页 > 编程语言 > 详细

java web文件上传 基于commons-fileupload-1.3.1.jar

时间:2016-08-18 14:20:39      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

上传文件的方法有很多种,我现在做的项目是使用Apache的fileupload。

首先我们需要commons-fileupload-1.3.1.jar的包。 maven在pom.xml导入,普通web项目放在WEB-INF的lib目录下

然后 commons-fileupload.jar 依赖于commons-io.jar,所以同理加入commons-fileupload.jar

 

下面是代码。 用的是spring mvc,功能在controller里实现 

重新写了一遍注释,代码应该能看的很清楚了

/*
 * 接收上传的文件,返回文件地址
 */
 //url 地址
@RequestMapping("/uploadify")
public void uploadFile(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws Exception {

    String type = request.getParameter("type");
    String ret_fileName = null;// 返回给前端已修改的图片名称

    // 临时文件路径
    String dirTemp = "/static/upload/temp";
    
    //图片存储相对路径
    String suitelogo = "";
    
    //设置图片存储相对路径
    //这里的type是前台传过来方便辨认是什么图片的参数,没有需要就不用判断
    if ("app".equals(type)) {
        suitelogo = "/static/upload/applogo";
    } else if ("suite".equals(type)) {
        suitelogo = "/static/upload/suitelogo";
    } else {
        suitelogo = dirTemp;
    }
    
    request.setCharacterEncoding("UTF-8");
    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();

    // 获取当前项目的根目录  tomcat的绝对路径/webapps/项目名
    String realPath = session.getServletContext().getRealPath("");
    
    
    //获取tomcat下的ROOT目录,通过root绝对路径和存储图片文件夹的相对路径创建目录 
    //mkdirs方法逐级创建目录。 mkdir只创建最后一级目录,前面目录不存在则不创建
    File realFile = new File(realPath);
    
    String rootPath = realFile.getParent() + "/ROOT";
    String normPath = rootPath + suitelogo;
    String tempPath = rootPath + dirTemp;

    File f = new File(normPath);
    File f1 = new File(tempPath);
    System.out.println(normPath);
    if (!f.exists()) {
        f.mkdirs();
    }

    if (!f1.exists()) {
        f1.mkdirs();
    }

    
    //创建文件解析对象
    DiskFileItemFactory factory = new DiskFileItemFactory();
    
    //设定使用内存超过5M时,将产生临时文件并存储于临时目录中 
    factory.setSizeThreshold(5 * 1024 * 1024); 
    
    // 设定存储临时文件的目录
    factory.setRepository(new File(tempPath)); 

    //创建上传文件实例
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");

    try {
        //解析request 成FileItem 因为支持多个文件上传,所以用list
        List<?> items = upload.parseRequest(request);
        Iterator<?> itr = items.iterator();

        while (itr.hasNext()) {
            
            //获取文件名
            FileItem item = (FileItem) itr.next();
            String fileName = item.getName();
            if (fileName != null) {
                fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
                fileName = getUUID() + fileName;
                ret_fileName = normPath + "/"+fileName;
            }
            
            //如果不是普通表单,则是文件上传表单,取二进制流写入本地
            if (!item.isFormField()) {

                try {
                    File uploadedFile = new File(normPath + "/" + fileName);
                    OutputStream os = new FileOutputStream(uploadedFile);
                    InputStream is = item.getInputStream();
                    byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度
                    int length = 0;
                    while ((length = is.read(buf)) > 0) {
                        os.write(buf, 0, length);
                    }
                    // 关闭流
                    os.flush();
                    os.close();
                    is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    // 将已修改的图片名称返回前台
    out.print(ret_fileName);
    out.flush();
    out.close();
}

//生成随机数字,防止文件重名
private String getUUID() {
    return UUID.randomUUID().toString();
}

 流程主要几个步骤

1.创建文件解析对象DiskFileItemFactory factory = new DiskFileItemFactory();

2.创建上传文件实例ServletFileUpload upload = new ServletFileUpload(factory);

3获取上传的文件明,并把文件存入本地

java web文件上传 基于commons-fileupload-1.3.1.jar

标签:

原文地址:http://www.cnblogs.com/Frank-zsx/p/5783505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!