Bootstrap

springMVC实现 MultipartFile 多文件上传,StandardMultipartHttpServletRequest上传文件,在请求中上传文件,比如上传图片

MultipartFile是springmvc官方提供的一个比较完善的文件上传组件,MultipartFile是一个组织接口它的实现类有

org.springframework.web.multipart.commons.CommonsMultipartFile
org.springframework.mock.web.MockMultipartFile
它在springmvc中的org.springframework.web.multipart这个包内,与org.springframework.web.multipart.commons和org.springframework.web.multipart.support包内的类接口组合使用该。

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

如果在依赖jar上有不是只要加入commons-fileupload的问题,在这里要解释下。因为这个jar包1.0 版本到1.1版本的时候把org.apache.commons.io.output.DeferredFileOutputStream.class移除了,所以要使用commons-io这个jar中的这个类来弥补。所以说如果上传你碰到这个问题

HTTP Status 500 - Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream,那就赶紧加入那个依赖吧。

在这里插入图片描述

这个是spring的

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="utf-8"></property>   
        <property name="maxUploadSize" value="10485760000"></property>  
        <property name="maxInMemorySize" value="40960"></property>  
   </bean>

如果是springboot的话,直接@Bean注入一下然后配置就完事了

@Bean
    CommonsMultipartResolver commonsMultipartResolver(){
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        commonsMultipartResolver.setDefaultEncoding("UTF-8");
        commonsMultipartResolver.setMaxUploadSize(Long.valueOf("10485760000").longValue());
        commonsMultipartResolver.setMaxInMemorySize(40960);
        return commonsMultipartResolver;
    }

光加入依赖还是远远不够的,在前台页面也需要改不然后台接收不到数据。默认的form提交是application/x-www-form-urlencoded而上传文件是把文件用2进制的方式传输默认的格式已经满足不了需求,就需要使用multipart/form-data格式来发送接收。

前端html中的form表单

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>上传多个文件 实例</h2>  
    <form action="/upload/filesUpload" method="post"  enctype="multipart/form-data">  
        <p>选择文件:<input type="file" name="files"></p>
        <p>选择文件:<input type="file" name="files"></p>
        <p><input type="submit" value="提交"></p>
    </form>  
</body>
</html>
//上传多文件的话,需在表单的input中加入multiple="multiple"。(可一次选择多个文件)

<form action="/upload/filesUpload" method="post" enctype="multipart/form-data">
        <input type="file" name="files" multiple="multiple" /><p>
        <input type="submit" value="提交" /><p>
        <input type="reset" value="清空" /><p>
</form>
//上传文件夹的话,需在表单input中加入webkitdirectory directory。(仅可以选择文件夹,文件夹内的文件也能成功上传)

<form action="/upload/filesUpload" method="post" enctype="multipart/form-data">
        <input type="file" name="files" multiple="multiple" webkitdirectory directory /><p>
        <input type="submit" value="提交" /><p>
        <input type="reset" value="清空" /><p>
</form>

controller中接收

单文件上传,注意MultipartFile的实例名要与页面中表单的name值一致。

@RequestMapping("/upload")
@Controller
public class FileController {
   @RequestMapping("/filesUpload")
    public ModelAndView fileUpload(HttpServletRequest request,@RequestParam("files") MultipartFile[] files) throws IOException {
        ModelAndView mv = new ModelAndView();
        String path=request.getServletContext().getRealPath("/");
        File file =new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
     if (upload!=null&&upload.length>0){
            for (int i=0;i<upload.length;i++){
                String filename = upload[i].getOriginalFilename();
                String uuid = UUID.randomUUID().toString().toUpperCase();
                filename = uuid+"_"+filename;
                upload[i].transferTo(new File(file,filename));
                mv.addObject("info","上传成功!");
                mv.setViewName("success");
            }
        }
        return mv;
    }
}

StandardMultipartHttpServletRequest上传文件,在请求中上传文件,比如图片

@PostMapping("upload")
public void upload(HttpServletRequest request, HttpServletResponse response){

    StandardMultipartHttpServletRequest httpServletRequest = (StandardMultipartHttpServletRequest) request;
    Enumeration<String> parameterNames = httpServletRequest.getParameterNames();
    System.out.println("-------------------ParameterNames------------------");
    while(parameterNames.hasMoreElements()){
        String key = parameterNames.nextElement();
        String value = httpServletRequest.getParameter(key);
        System.out.println("key = " + key);
        System.out.println("value = " + value);
    }
    System.out.println("-------------------AttributeNames------------------");
    Enumeration<String> attributeNames = httpServletRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()){
        String key = attributeNames.nextElement();
        System.out.println("key = " + key);
    }
    System.out.println("-------------------HeaderNames------------------");
    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = headerNames.nextElement();
        String value = httpServletRequest.getHeader(key);
        System.out.println(String.format("key: %s, value:%s",key,value));
    }
    System.out.println("-------------------FileNames------------------");
    Iterator<String> iterator = httpServletRequest.getFileNames();
    while (iterator.hasNext()) {
        MultipartFile file = httpServletRequest.getFile(iterator.next());
        String fileNames = file.getOriginalFilename();
        int split = fileNames.lastIndexOf(".");
        System.out.println("fileNames = " + fileNames);
    }
}

我这边是要从request中取图片,所以直接到下面获取MultipartFile 的地方,这里我遇到一个问题,我传了2张图片,但是用iterator获取的时候只拿到了一张,我这边改了一下

@RequestMapping('batchUpload')
    ResponseMessage batchUpload(HttpServletRequest request, @RequestParam("uploadedfiles[]") MultipartFile[] files, @RequestParam String companyCode,@RequestParam String itemCode) {
        TtxSession sess = getSession(request)
        StandardMultipartHttpServletRequest httpServletRequest = (StandardMultipartHttpServletRequest) request;
        return trSvc.translate(session,exItemSvc.batchUpload(sess, httpServletRequest, companyCode,itemCode))
    }
 ResponseMessage batchUpload(TtxSession sess, StandardMultipartHttpServletRequest standardMultipartHttpServletRequest, String companyCode, String itemCode) {
        if (!companyCode) {
            return ResponseMessageFactory.error(sess, InventoryMessages.MSG_INVT_0119) //货主参数不存在
        }
        List<MultipartFile> multipartFileList = new ArrayList<>()
        multipartFileList = standardMultipartHttpServletRequest.getFiles("file")

        Set<String> errors = new HashSet<>()
        multipartFileList?.each {
            ResponseMessage rsp = this.upload(sess, it, companyCode, itemCode)
            if (rsp.hasError()) errors.add(rsp.msg)
        }
        if (errors) {
            String text = errors.collect({ trSvc.getText(sess, it) }).join('、')
            return ResponseMessageFactory.error(sess, InventoryMessages.MSG_INVT_0136, null, text) //部分图片上传失败:${0}
        }
        return ResponseMessageFactory.success(sess)
    }

上面是手动获取的方式,但是其实用注解就可以实现了,
@RequestPart(“file”) MultipartFile[] files这里的file是请求中文件的key

拿个别人的postman的Demo,这里的uploadFile就相当于file这个key
在这里插入图片描述
在这里插入图片描述

;