基于MultipartFile实现多文件上传

用Spring下的MultipartFile实现多文件上传功能

Spring自带了多文件上传功能,主要是spring下的MultipartFile实现的,在实现多文件上传之前,要保证导入了Spring的包文件。以下是我的项目中导入Spring包。

pom.xml


org.springframework
spring-web


org.springframework
spring-context


org.springframework
spring-core


org.springframework
spring-webmvc

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3</version>
</dependency>

在Spring中配置文件上传:

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

文件上传后台处理:

@RequestMapping(value = "/api/{sessionid}/documents", method = RequestMethod.POST)
 public @ResponseBody
 ResultInfo<String> upload(@PathVariable("sessionid")String sessionID,
            @RequestParam("category")String category,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {

      ResultInfo<String> info = new ResultInfo<String>();

    try{

          MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

          // 1 得到上传的文件
          List<MultipartFile> mFiles = multipartRequest.getFiles("files");

         for (MultipartFile mFile : mFiles) {

          if (mFile == null) {

              return ResultInfo.getIllegalDataAccess();
          }

          // 2 得到上传服务器的路径
          String path = request.getSession().getServletContext()
                    .getRealPath("/") +  "..\\teworks-docs";

          // 新建文件目录
          File file = new File(path);
          if (!file.exists()) {
              file.mkdir();
          }

          // 3 得到上传的文件的文件名
          String filename = mFile.getOriginalFilename();

          InputStream inputStream = mFile.getInputStream();

          byte[] b = new byte[1048576];

          int length = inputStream.read(b);
          String docID = UUID.get();

          path += "\\" + docID + "." + StringUtils.getFilenameExtension(filename);

          // 4文件流写到服务器端
          FileOutputStream outputStream = new FileOutputStream(path);

          // 5 保存document对象
          Document doc = new Document();
          doc.setId(docID);

          doc.setDocGroupID(category);

          if(dirID != null) {
              doc.setDocumentDirectory(this.docDirService.findByID(dirID));
          } 
          doc.setFileSize(length);
          doc.setFullName(DocumentHelper.getFileName(filename));
          doc.setMimeType(mFile.getContentType());
          Document ret = this.docService.add(doc);

          // 6 存储文件
          outputStream.write(b, 0, length);
          inputStream.close();
          outputStream.close();
        }

          // 7 返回结果
          info.setErrorCode(0);
          info.setResult(rets);

          return info;
    } catch(RuntimeException e){

        logger.error(e.getMessage(), e.fillInStackTrace());

    } catch (Exception e){
        logger.error(e.getMessage(), e.fillInStackTrace());
    }

      return ResultInfo.getIllegalDataAccess();
}

这里获取前台传过来的input的name必须是files,否则是获取不到文件参数的。
前台配置如下:

<form action=""  enctype="multipart/form-data" method= "post">
    <input type="file" name="files" class="btn" multiple >
    <button type="button" id="document-upload-submit" class="btn btn-primary">上传</button>
</form>

以上的type=“file”的input 中加入multiple则支持前台多选文件,这里的name必须为files,前后台要保持一次。

到这里为止,就能实现多文件上传了!

本站总访问量