Java教程

Java 多文件上传(transferTo)

本文主要是介绍Java 多文件上传(transferTo),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

文件上传在application.properties中配置文件路径

###文件上传地址
file.upload.url=/upload/file

文件上传代码:


  //本地路径
  @Value("${file.upload.url}")
  private String uploadFilePath;
   /*
     * @param file 文件列表
     * @return
     */
    @RequestMapping("/upload")
    public Object uploadOtherFilesNew(@RequestParam("file") MultipartFile[] file) {

        Map<String,Object> map = new HashMap<>();
        map.put("status",200);
        List<Map<String, Object>> result = new ArrayList<>();
        if (file != null && file.length > 0) {
            Arrays.asList(file).stream().forEach(files -> result.add(httpUpload(files)));
        }
        map.put("data",result);
        return map;
    }

    public Map<String,Object> httpUpload(MultipartFile file)  {
        Map<String, Object> result = new HashMap<>();
        //返回文件名乱码问题
        //HttpHeaders headers = new HttpHeaders();
        //MediaType mediaType = new MediaType("text","html", Charset.forName("utf-8"));
        //headers.setContentType(mediaType);
     //return new ResponseEntity<String>(js,headers, HttpStatus.OK);
     
        //本地文件路径
        String fileDirPath = new String("src/main/resources/" + uploadFilePath+"_"+UUID.randomUUID().toString().replace("-", "").toLowerCase());
        File fileDir = new File(fileDirPath);
        //String[] originalFilename = file.getOriginalFilename().split("\\."); // 文件名
        System.out.println("fileDir.getAbsolutePath()======"+fileDir.getAbsolutePath());
        File dest = new File(fileDir.getAbsolutePath() + File.separator+'/'+  file.getOriginalFilename());
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            result.put("url",dest);
            result.put("fileName",file.getOriginalFileName());
            result.put("success",1);
            result.put("result","文件上传成功");
        } catch (Exception e) {
            log.error("{}",e);
            result.put("success",2);
            result.put("result","程序错误,请重新上传");
        }
        return result;
    }

 

这篇关于Java 多文件上传(transferTo)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!