Java-使用commons-fileupload做文件上传

方法一

1.在spring-mvc项目中引入commons-fileupload.jar包和commons-io.jar包还有jspSmartUpload.jar包,并在webmvc-config.xml配置文件中添加,如下代码(主要解决上传文件乱码问题):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
    …………
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/>
    …………

2.jsp页面form表单,设置如下:

<form name="form1" id="form1" enctype="multipart/form-data" method="post"
      action="${ctx }/manage/manageInfo/phone/new.do">

</form>

3.编写上传文件代码:

    /**
     * 新增机型
     * @author luowei
     * @createTime 2012-1-12
     * @param phone
     * @param request
     * @param result
     * @return
     */
    @RequestMapping(value = "/new")
    public String newPhone(Phone phone,DefaultMultipartHttpServletRequest request,
                           HttpServletResponse response) {
        MultipartFile file=request.getFile("phoneimage1");
        String fileName = file.getOriginalFilename();
        String path = request.getRealPath("images/phone");
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);    //上传目标文件
        } catch (Exception e) {
            e.printStackTrace();
        }
        phone.setPhoneImage("/ttpod/images/phone/"+fileName);
        phone.setPhonebrand(new Phonebrand(Integer.parseInt((String)request.getParameter("brandName"))));
        phone.setPlatform(new Platform(Integer.parseInt((String)request.getParameter("platformName"))));
        phone.setPhoneAddDate(DateUtil.datetimeToDate());
        this.phoneManageService.save(phone);
        //处理其它异外情况,。。。。。。。
        String currentPage = (String) this.getSessionAttribute(request,"currentPage");
        this.sendRedirect(response, currentPage);
        return null;
    }

方法二

直接解析HttpServletRequest,示例代码如下,(表单格式仍然为:enctype=”multipart/form-data”):

    /**
     * 新增机型
     *
     * @param phone
     * @param request
     * @param result
     * @return
     * @author luowei
     * @createTime 2012-1-12
     */
    @RequestMapping(value = "/new")
    public String newPhone(Phone phone, HttpServletRequest request, HttpServletResponse response) {
        Phone phone = new Phone();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            request.setCharacterEncoding("utf-8");
            List items = upload.parseRequest(request); //解析HttpServletRequest
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) //如果是普通表单字段
                {
                    String name = item.getFieldName(); //取得表单中字段的名
                    String value = item.getString("utf-8"); //取得表单中字段的值
                    if (name.equals("phoneName")) {
                        phone.setPhoneName(value);
                    }
                    if (name.equalsIgnoreCase("brandName")) {
                        phone.setPhonebrand(new Phonebrand(Integer.parseInt(value))); //将指定的手机品牌关联到机型
                    }
                    if (name.equals("platformName")) {
                        phone.setPlatform(new Platform(Integer.parseInt(value))); //将指定的手机平台关联到机型
                    }
                    if (name.equals("phoneHeadName")) {
                        phone.setPhoneName(value);
                    }
                    if (name.equals("phoneResolution")) {
                        phone.setPhoneName(value);
                    }
                    if (name.equals("phoneStatus")) {
                        phone.setPhoneStatus(Integer.parseInt(value));
                    }
                    if (name.equals("phoneDesc")) {
                        phone.setPhoneDesc(Integer.parseInt(value));
                    }
                } else if (!item.isFormField()) //如果不是普通表单字段,即文件字段
                {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    //System.out.println(fieldName+":"+fileName+":"+contentType+":"+sizeInBytes);
                    String path = request.getRealPath("images/phone");
                    File uploadedFile = new File(path, GetId.getNewId() + fileName); //创建一个上传文件对象
                    try {
                        item.write(uploadedFile); //将要上传的文件对象写到item
                        phone.setPhoneImage("/ttpod/images/phone/" + uploadedFile.getName());
                    } catch (Exception e) {
                        e.printStackTrace();
                        phone.setPhoneImage("");
                    }
                    System.out.println(path);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        phone.setPhoneAddDate(DateUtil.datetimeToDate()); //给phone对象的添加日期字段设置值
        this.phoneManageService.save(phone); //执行保存
        String currentPage = (String) this.getSessionAttribute(request, "currentPage");
        this.sendRedirect(response, currentPage);
        return null;
    }

版权所有,转载请注明出处 luowei.github.io.