java实现文件上传(包含多文件上传)

  • 页面
<form method="post"  action="/DuoFile" enctype="multipart/form-data">
   <div class="form-group">
       <div class="label">
           <label>图片:</label>
       </div>
       <div class="field">
           <input type="text" th:value="1" name="lib_id" hidden="hidden"/>
           <input type="file" name="img" class="input" value=""  required/>
       </div>
   </div>
</form>  
  • 控制器
@RequestMapping("/DuoFile")
@ResponseBody
    public String dataPicAdd(@RequestParam(value = "submit",required = false) String submit,
                             @RequestParam(value = "img",required = false) List<MultipartFile> uploadImage,
                             Model model)  throws Exception{
        System.out.println("DuoFile:");
        String facePath = null;
        if (submit!=null) {
            System.out.println("图片数量:"+uploadImage.size());
            JSONObject json = new JSONObject();
            if (uploadImage == null) {
                return "上传失败,上传图片数据为空";
            } else {
                for (int i=0;i<uploadImage.size();i++){
                    String suffix = uploadImage.get(i).getContentType().toLowerCase();//图片后缀,用以识别哪种格式数据
                    suffix = suffix.substring(suffix.lastIndexOf("/") + 1);

                    if (suffix.equals("jpg") || suffix.equals("jpeg") || suffix.equals("png") || suffix.equals("gif")) {
                        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
                        //保存路径
                        String imgFilePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/images";
                        File targetFile = new File(imgFilePath, fileName);
                        if (!targetFile.getParentFile().exists()) { //判断父级路径是否存在
                            targetFile.getParentFile().mkdirs();//创建目录
                        }
                        //保存
                        uploadImage.get(i).transferTo(targetFile);
                        String sTestsetFile = facePath;
                       return"上传图片成功";
                    } else {
                        return "上传图片格式非法";
                    }
                }
            }
        }
    }
  • maven
<dependency>
   <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

小白一枚,遇到问题,欢迎评论

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值