Spring上传文件,图片,以及常见的问题

1. 在工程依赖库下添加文件上传jar包

  commons-fileupload-1.2.2.jar
  commons-io-2.4.jar

 

2.在springMVC配置文件中配置视图解析multipartResolver 

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

  这里有个问题需要注意一下,Bean 的id必须为multipartResolver,因为在项目初始化的时候,Spring容器会通过这个id来进行注入,下面是Spring源码:


   
public static final String MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver"; /** MultipartResolver used by this servlet */ private MultipartResolver multipartResolver; /* 省略一大堆代码 */ /** * Initialize the MultipartResolver used by this class. * <p>If no bean is defined with the given name in the BeanFactory for this namespace, * no multipart handling is provided. */ private void initMultipartResolver(ApplicationContext context) { try { this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class); if (logger.isDebugEnabled()) { logger.debug("Using MultipartResolver [" + this.multipartResolver + "]"); } } catch (NoSuchBeanDefinitionException ex) { // Default is no multipart resolver. this.multipartResolver = null; if (logger.isDebugEnabled()) { logger.debug("Unable to locate MultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME + "': no multipart request handling provided"); } } }

   接下来,我们测试一下如果写错之后会报什么错误

  

 

  上面只是DEBUG, 查看源码就会知道会DEBUG输出这一句,

  下面是具体报的错误:预期的MultipartHttpServletRequest:是否配置了MultipartResolver?

 

 

 

 下面依次是jsp代码和后台实现上传的java代码:

  

<form id="userForm" name="userForm" method="post"
        action="${pageContext.request.contextPath }/user/useraddsave.html"
        enctype="multipart/form-data">
            <div>
                <label for="a_idPicPath">证件照:</label> <input type="file"
                    name="a_idPicPath" id="a_idPicPath" /> <font color="red"></font>
            </div>
            <div class="providerAddBtn">
                <input type="button" name="add" id="add" value="保存"> <input
                    type="button" id="back" name="back" value="返回">
            </div>
        </form>

 

 

//保存新增用户信息
    @RequestMapping(value="/useraddsave.html",method=RequestMethod.POST)
    public String addUserSave(User user,HttpServletRequest request,@RequestParam(value="a_idPicPath",required=false) MultipartFile multipartFile){
        
        if(!multipartFile.isEmpty()){
            String path = "/statics"+File.separator+"upload"; //文件或者图片上传到的位置
            String oldName = multipartFile.getOriginalFilename(); //上传的文件名
            String prefix = FilenameUtils.getExtension(oldName); //文件的后缀名
            int maxSize =5000000;
            if(multipartFile.getSize()<maxSize){
                if(prefix.equalsIgnoreCase("jpg")|| prefix.equalsIgnoreCase("png")){
                    String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal."+prefix; // 为避免文件名一样随机生成的文件名保存在服务器
                    File targetFile = new File(path,fileName);
                    if(!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    try {
                        multipartFile.transferTo(targetFile); //开始上传
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        request.setAttribute("uploadFileError", "上傳出現異常,上傳失敗");
                    }
                    String idPicPath= path+File.separator+fileName;
                    user.setIdPicPath(idPicPath);
                    user.setCreationDate(new Date());
                    userService.add(user);
                    return "redirect:/user/userlist.html";
                } else {
                    request.setAttribute("uploadFileError", "文件格式錯誤,上傳失敗");
                }
            } else {
                request.setAttribute("uploadFileError", "文件太大,上傳失敗");
            }
        }  
        return "useradd";//新增失败返回到useradd.jsp
    }

   方法需要添加参数 @RequestParam(value="a_idPicPath",required=false) MultipartFile multipartFile

 

              The end......

 

posted @ 2017-09-13 16:30  孤独是1态度  阅读(554)  评论(0编辑  收藏  举报