SpringMVC 文件上传配置,多文件上传,使用的MultipartFile

    xiaoxiao2021-11-06  84

    SpringMVC 文件上传配置,多文件上传,使用的MultipartFile

    如何使用SpringMVC进行表单上的文件上传以及多个文件同时上传的步骤 一、配置文件: SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们首先要配置MultipartResolver:用于处理表单中的file commons-fileupload-1.3.1.jar commons-io-2.4.jar <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->      <bean id="multipartResolver"             class="org.springframework.web.multipart.commons.CommonsMultipartResolver">             <!-- 默认编码 -->           <property name="defaultEncoding" value="utf-8" />             <!-- 文件大小最大值 -->           <property name="maxUploadSize" value="10485760000" />             <!-- 内存中的最大值 -->           <property name="maxInMemorySize" value="40960" />         </bean>   其中属性详解: defaultEncoding="UTF-8" 是请求的编码格式,默认为iso-8859-1 maxUploadSize="5400000" 是上传文件的大小,单位为字节 uploadTempDir="fileUpload/temp" 为上传文件的临时路径

    二、创建一个简单的上传表单:

    [html] view plain copy print ? <body>  <h2>文件上传实例</h2>      <form action="fileUpload.html" method="post" enctype="multipart/form-data">      选择文件:<input type="file" name="file">      <input type="submit" value="提交">   </form>      </body>  注意要在form标签中加上 enctype="multipart/form-data" 表示该表单是要处理文件的,这是最基本的东西,很多人会忘记然而当上传出错后则去找程序的错误,却忘了这一点 三、编写上传控制类 1、创建一个控制类: FileUploadController和一个返回结果的页面list.jsp 2、编写提交表单的action: /**保存数据      * 网站图片管理      * **/     @RequestMapping(value = "savewebpic")     public String savewebpic(Model model,             @RequestParam(required = false) String id,             @RequestParam(required = false) String pid,             @RequestParam(required = false) String name,             @RequestParam(value = "imageFile", required = false) MultipartFile imageFile,             @RequestParam(required = false) Integer rank,             @RequestParam(required = false) String source,             @RequestParam(required = false) String remark,             @RequestParam(required = false) Integer pageno) {                  try {             String picUrl = null;             if(imageFile!=null&&imageFile.getSize()>0){                 picUrl  = UploadUtils.uploadFile(imageFile, id,"imgs/websitepic/");             }else{                 picUrl = null;             }             model.addAllAttributes(webdataService.savewebpic(id,pid,name,picUrl,rank,source,remark));             model.addAttribute("pid", pid);             model.addAttribute("source", source);             //model.addAttribute(Constants.status, Constants.ResultType.SUCCESS.v());             //model.addAttribute(Constants.message, "操作成功!");         } catch (Exception e) {             log(e);             model.addAttribute(Constants.status, Constants.ResultType.FAIL.v());             model.addAttribute(Constants.errormessage, e.getMessage());             e.printStackTrace();         }                  return "redirect:/webdata/webpiclist";     } /**上传文件**/ public class UploadUtils {         public static String uploadFile(MultipartFile file, String id,String prefixPath) throws IllegalStateException, IOException {         String bannerBasePath = ConfigUtils.getUploadBasePath() + prefixPath+"/";         String datepath = getYYYYMM();         String nfileName = id + "-" + new Date().getTime() + ".jpg";         String filepath = bannerBasePath + datepath;                  File targetFile = new File(filepath, nfileName);         if (!targetFile.exists()) {             targetFile.mkdirs();         } else {             targetFile.delete();         }         file.transferTo(targetFile); // 通过MultipartFile的transferTo(File dest)这个方法来转存文件到指定的路径。         return datepath + "/" + nfileName;     } } MultipartFile类常用的一些方法: String getContentType()//获取文件MIME类型 InputStream getInputStream()//后去文件流 String getName() //获取表单中文件组件的名字 String getOriginalFilename() //获取上传文件的原名 long getSize() //获取文件的字节大小,单位byte boolean isEmpty() //是否为空 void transferTo(File dest) //保存到一个目标文件中。 四.多文件上传。 多文件上传其实很简单,和上传其他相同的参数如checkbox一样,表单中使用相同的名称,然后action中将MultipartFile参数类定义为数组就可以。 接下来实现: /***      * 保存文件      * @param file      * @return      */      private boolean saveFile(MultipartFile file) {          // 判断文件是否为空          if (!file.isEmpty()) {              try {                  // 文件保存路径                  String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"                          + file.getOriginalFilename();                  // 转存文件                  file.transferTo(new File(filePath));                  return true;              } catch (Exception e) {                  e.printStackTrace();              }          }          return false;      }  3、编写action:      @RequestMapping("filesUpload")      public String filesUpload(@RequestParam("files") MultipartFile[] files) {          //判断file数组不能为空并且长度大于0          if(files!=null&&files.length>0){              //循环获取file数组中得文件              for(int i = 0;i<files.length;i++){                  MultipartFile file = files[i];                  //保存文件                  saveFile(file);              }          }          // 重定向          return "redirect:/list.html";      } 

    或者上述的 @RequestParam(value = "files", required = false) MultipartFile[]files 由下列替换

    MultipartHttpServletRequest request01=(MultipartHttpServletRequest) request; List<MultipartFile> fileList=request01.getFiles("files");

    转载请注明原文地址: https://ju.6miu.com/read-678067.html

    最新回复(0)