java文件上传映射路径,springboot单文件上传到指定目录分类并返回访问路径

业务逻辑就不写service层了,方便展示.还没放到linux中测试....

问题解决

使用ubuntu运行测试,并设置yml里的变量 path: /upload/出现了如下异常

FileNotFoundException: /upload/jpg/1595516455456eyes.jpg (No such file or directory)

手动创建jpg子目录后出现新的异常

FileNotFoundException: /upload/jpg/1595516494684eyes.jpg (Permission denied)

给/upload文件夹设置权限0777 上传成功,输入返回的url并成功访问

{

"code": 200,

"msg": "操作成功",

"data": "http://192.168.153.128:8086/archive/jpg/1595517483320eyes.jpg"

}

上传md格式的文件,成功创建了md目录,保存并返回url,输入url浏览器自动下载

c453fbac5ed03601b5c3646e40b5faa3.png

欢迎大佬题出更好意见

yml和配置类

yuan:

file:

root:

## 定义文件保存的路径

path: D:developupload

# ..... 省略其他无关配置

spring:

servlet:

multipart:

enabled: true

max-file-size: 10MB # 设置文件最大大小

@Configuration

public class WebMvcConfig implements WebMvcConfigurer {

@Value("${yuan.file.root.path}")

public String fileRootPath;

/**

* 资源映射:把请求的/archive/** 映射到该文件根路径

*/

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/archive/**").addResourceLocations("file:" + fileRootPath);

}

}

Controller层

@Api("文件操作相关")

@RestController

public class FileController {

@Value("${yuan.file.root.path}")

public String fileRootPath;

@ApiOperation("文件上传")

@PostMapping("/upload")

public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

String filePath = ""; // 文件保存的位置

String urlPath = "";// 文件web浏览路径

Assert.isTrue(!file.isEmpty(), "文件为空");

// 原始名 以 a.jpg为例

String originalFilename = file.getOriginalFilename();

// 获取后缀并拼接'/'用于分类,也可以用日期 例: suffix = "jpg/"

String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1) + "/";

// 加上时间戳生成新的文件名,防止重复 newFileName = "1595511980146a.jpg"

String newFileName = System.currentTimeMillis() + originalFilename;

filePath = fileRootPath + suffix + newFileName;

System.out.println(filePath);

try {

File file1 = new File(filePath);

if (!file1.exists()) file1.mkdirs(); // 要是目录不存在,创建一个

file.transferTo(file1); // 保存起来

urlPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/archive/" + suffix + newFileName;

} catch (Exception e) {

e.printStackTrace();

}

return Result.succ(urlPath);

}

}

结果

801d2dc713a6f015ba231cca5fa15bf0.png

b29d6e1d0b10e0e196cce987887f7d8a.png

874ee21bf872bf1f9567700343c93b4d.png

fdd84198bb9c8ac869c0cc5c363f09c8.png

参考

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值