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

小灰灰 2024-04-18 20:06 198阅读 0赞
  • 页面











  • 控制器

    @RequestMapping(“/DuoFile”)
    @ResponseBody

    1. public String dataPicAdd(@RequestParam(value = "submit",required = false) String submit,
    2. @RequestParam(value = "img",required = false) List<MultipartFile> uploadImage,
    3. Model model) throws Exception{
    4. System.out.println("DuoFile:");
    5. String facePath = null;
    6. if (submit!=null) {
    7. System.out.println("图片数量:"+uploadImage.size());
    8. JSONObject json = new JSONObject();
    9. if (uploadImage == null) {
    10. return "上传失败,上传图片数据为空";
    11. } else {
    12. for (int i=0;i<uploadImage.size();i++){
    13. String suffix = uploadImage.get(i).getContentType().toLowerCase();//图片后缀,用以识别哪种格式数据
    14. suffix = suffix.substring(suffix.lastIndexOf("/") + 1);
    15. if (suffix.equals("jpg") || suffix.equals("jpeg") || suffix.equals("png") || suffix.equals("gif")) {
    16. String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
    17. //保存路径
    18. String imgFilePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/images";
    19. File targetFile = new File(imgFilePath, fileName);
    20. if (!targetFile.getParentFile().exists()) { //判断父级路径是否存在
    21. targetFile.getParentFile().mkdirs();//创建目录
    22. }
    23. //保存
    24. uploadImage.get(i).transferTo(targetFile);
    25. String sTestsetFile = facePath;
    26. return"上传图片成功";
    27. } else {
    28. return "上传图片格式非法";
    29. }
    30. }
    31. }
    32. }
    33. }
  • maven


    net.sf.json-lib
    json-lib
    2.4
    jdk15


    org.springframework.boot
    spring-boot-starter-web

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

发表评论

表情:
评论列表 (有 0 条评论,198人围观)

还没有评论,来说两句吧...

相关阅读

    相关 文件

    现象: 实现多文件上传: ![这里写图片描述][SouthEast] 解决办法: 1:在页面提交表单加上如下代表表单中有文件上传 ![这里写图片描述][Sou