原创

Spring MVC 中上传文件的多种实现及区别

温馨提示:
本文最后更新于 2016年11月30日,已超过 2,943 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

1.普通方式(没有配置multipartResolver)

/**
     * @Description 上传文件
     * @author zhangyd
     * @date 2015年12月1日 下午3:02:23
     * @return
     * @throws Exception
     */
    @RequestMapping("/uploadFile")
    @ResponseBody
    public Object uploadFile(HttpServletRequest request) throws Exception {
        String path = LoadSystemProperties.UPLOAD_FILES_PATH;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        //获取图片url地址
        String fileName = "";// 文件名称
        /**上传文件处理内容**/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        sfu.setHeaderEncoding("UTF-8"); // 处理中文问题
        sfu.setSizeMax(1024 * 1024); // 限制文件大小
        try {
            List<FileItem> fileItems = sfu.parseRequest(request); // 解码请求
            for (FileItem fi : fileItems) {
                String name = fi.getName();
                if (name == null) {
                    continue;
                }
                fileName = UUID.randomUUID() + name.substring(name.lastIndexOf("."), name.length());
                fi.write(new File(path, fileName));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取图片url地址
        return path + "\\" + fileName;
    }


注:以上使用必须是在没有配置multipartResolver的前提下,配置multipartResolver后将会获取不到


这个问题只需要了解下SpringMVC中CommonsMultipartResolver的处理源码就会明白

/**
 * Parse the given servlet request, resolving its multipart elements.
 * @param request the request to parse
 * @return the parsing result
 * @throws MultipartException if multipart resolution failed.
 */
protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
	String encoding = determineEncoding(request);
	FileUpload fileUpload = prepareFileUpload(encoding);
	try {
		List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
		return parseFileItems(fileItems, encoding);
	}
	catch (FileUploadBase.SizeLimitExceededException ex) {
		throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
	}
	catch (FileUploadException ex) {
		throw new MultipartException("Could not parse multipart servlet request", ex);
	}
}

因为,配置完CommonsMultipartResolver之后,实际上SpringMVC已经对当前的HttpServletRequest 处理过了;因此,当再次通过sfu.parseRequest(request); // 解码请求获取请求中的文件时,就会获取不到了。

2.通过SpringMVC的multipartResolver处理器获取注:

必须配置以下内容

<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<property name="defaultEncoding" value="UTF-8" />
	<!-- 指定所上传文件的总大小不能超过100MB。注意maxUploadSize属性的限制不
        是针对单个文件,而是所有文件的容量之和 -->
	<!-- <property name="maxUploadSize" ><value>104857600</value></property> -->
	<!-- <property name="uploadTempDir" value="E:\temp"></property> -->
	<!-- <property name="resolveLazily"></property> -->
	<!-- <property name="servletContext"></property> -->
	<!-- <property name="maxInMemorySize"></property> -->
</bean>

1).

public void upload(HttpServletRequest request) {
        // 转型为MultipartHttpRequest
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> fileList = multipartRequest.getFiles("file");
            for (MultipartFile mf : fileList) {
                if (!mf.isEmpty()) {
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2).

/**
     * @param files
     * @return
     * @throws Exception
     * @Description 上传文件
     * @author zhangyd
     * @date 2015年12月1日 下午3:02:23
     */
    @RequestMapping("/uploadFile2")
    @ResponseBody
    public Object uploadFile(@RequestParam(value = "file") MultipartFile[] files) throws Exception {
        String path = LoadSystemProperties.UPLOAD_FILES_PATH;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        for (MultipartFile fi : files) {
            path = FileUtil.getUploadFilePath(fi);
        }
        //获取图片url地址z
        return path;
    }


正文到此结束
本文目录