加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java利用MultipartFile实现上传多份文件的代码

发布时间:2020-12-14 19:39:29 所属栏目:Java 来源:网络整理
导读:配置文件 !-- 文件上传 -- bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" property name="defaultEncoding" value="utf-8"/property property name="maxUploadSize" value="10485760000"/proper

配置文件

<!-- 文件上传 -->
 <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>

form表单

<form action="xxx.do" method="post" multiple="multiple"">
    <input type="file" id="file" name="filename" multiple="multiple" value="">
    <input type="file" id="file" name="filename" multiple="multiple" value="">
    <input type="submit" value="上传">
</form>

java后台 接受示例

 @RequestMapping("xxx")
 public String fileImgSave(@RequestParam("filename") MultipartFile[] files,HttpServletRequest request){
 //保存文件的路径
 String realPath = request.getSession().getServletContext().getRealPath("/imgssss");
 File path = new File(realPath);
 if(!path.exists()){
  path.mkdirs();
 }
        //判断file数组不能为空并且长度大于0
        if(files != null && files.length > 0){
          //循环获取file数组中得文件
          for(int i = 0;i < files.length;i++){
            MultipartFile file = files[i];
            //保存文件
            if (!file.isEmpty()){
             try {
               //转存文件 file.getOriginalFilename();文件原名称包括后缀名
               file.transferTo(new File(realPath+"/img"+i+".png"));
             } catch (IOException e) {
               e.printStackTrace();
             }
           }
          }
        }

 return "ok";
 }

MultipartFile常用方法 记录

文件类型值 getContentType()
文件原始名称包括后缀名 getOriginalFilename()
表单中文件组件对应name值 getName()
保存到一个目标文件中 transferTo()
文件是否为空 isEmpty()
文件大小单位为k getSize() 

总结

以上所述是小编给大家介绍的Java利用MultipartFile实现上传多份文件的代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读