springboot上传文件法获取文件路径问题

问题描述:

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

解决方案:

//获取跟目录
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()) path = new File("");
System.out.println("path:"+path.getAbsolutePath());

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

 

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

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

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

具体项目实战:

/**
 * 处理文件上传
 */
@RequestMapping("/remoteupload")
@ResponseBody
public String douploadRemote(HttpServletRequest request, @RequestParam("file") MultipartFile multipartFile) {
 
    if (multipartFile.isEmpty()) {
        return "file is empty.";
    }
 
    String originalFilename = multipartFile.getOriginalFilename();
    String newFileName = UUIDHelper.uuid().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf(".") - 1);
    File file = null;
    try {
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        File upload = new File(path.getAbsolutePath(), "static/tmpupload/");
        if (!upload.exists()) upload.mkdirs();
        String uploadPath = upload + "\\";
        file = new File(uploadPath + newFileName);
        multipartFile.transferTo(file);
 
        // 提交到另一个服务
        FileSystemResource remoteFile = new FileSystemResource(file);
        // package parameter.
        MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
        multiValueMap.add("file", remoteFile);
 
        String remoteaddr = "http://localhost:12345/test/doupload";
        String res = restTemplate.postForObject(remoteaddr, multiValueMap, String.class);
 
        return res;
    } catch (Exception e) {
        return "file upload error.";
    } finally {
        try{
            file.delete();
        } catch (Exception e) {
            // nothing.
        }
        return "ok";
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值