问题描述:

    在开发一个springboot的项目时,在项目部署的时候遇到一个问题:就是我将项目导出为jar包,然后用java -jar 运行时,项目中文件上传的功能无法正常运行,其中获取到存放文件的目录的绝对路径的值为空,文件无法上传

    解决方案:

    1. //获取跟目录
    2. File path = new File(ResourceUtils.getURL("classpath:").getPath());
    3. if(!path.exists()) path = new File("");
    4. System.out.println("path:"+path.getAbsolutePath());
    5. //如果上传目录为/static/images/upload/,则可以如下获取:
    6. File upload = new File(path.getAbsolutePath(),"static/images/upload/");
    7. if(!upload.exists()) upload.mkdirs();
    8. System.out.println("upload url:"+upload.getAbsolutePath());
    9. //在开发测试模式时,得到的地址为:{项目跟目录}/target/static/images/upload/
    10. //在打包成jar正式发布时,得到的地址为:{发布jar包目录}/static/images/upload/

    另外使用以上代码需要注意,因为以jar包发布时,我们存储的路径是与jar包同级的static目录,因此我们需要在jar包目录的application.properties配置文件中设置静态资源路径,如下所示:

    1. #设置静态资源路径,多个以逗号分隔
    2. resources.static-locations=classpath:static/,file:static/

    以jar包发布springboot项目时,默认会先使用jar包跟目录下的application.properties来作为项目配置文件。
    具体项目实战:

    1. /**
    2. • 处理文件上传
    3. */
    4. @RequestMapping("/remoteupload")
    5. @ResponseBody
    6. public String douploadRemote(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile) {
    7. if (multipartFile.isEmpty()) {
    8. return "file is empty.";
    9. }
    10. String originalFilename = multipartFile.getOriginalFilename();
    11. String newFileName = UUIDHelper.uuid().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf(".") - 1);
    12. File file = null;
    13. try {
    14. File path = new File(ResourceUtils.getURL("classpath:").getPath());
    15. File upload = new File(path.getAbsolutePath(), "static/tmpupload/");
    16. if (!upload.exists()) upload.mkdirs();
    17. String uploadPath = upload + "\";
    18. file = new File(uploadPath + newFileName);
    19. multipartFile.transferTo(file);
    20. // 提交到另一个服务
    21. FileSystemResource remoteFile = new FileSystemResource(file);
    22. // package parameter.
    23. MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
    24. multiValueMap.add("file", remoteFile);
    25. String remoteaddr = "http://localhost:12345/test/doupload";
    26. String res = restTemplate.postForObject(remoteaddr, multiValueMap, String.class);
    27. return res;
    28. } catch (Exception e) {
    29. return "file upload error.";
    30. } finally {
    31. try{
    32. file.delete();
    33. } catch (Exception e) {
    34. // nothing.
    35. }
    36. return "ok";
    37. }
    38. }