Spring Boot文件上传

本文介绍如何在SpringBoot 2.0.5中配置文件上传功能,并通过http直接访问上传的文件,如图片和PDF的直接显示,Word和Excel的直接下载。详细解释了配置静态文件路径的方法,以及使用RestController实现文件上传的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring boot 2.0.5
要实现文件上传并直接访问(查看/下载)

配置静态文件路径

application.properties

uploadPath=/opt/data1/uploads/
## 上传路径设置为静态资源路径,可以通过http直接访问,比如图片/pdf会直接显示在浏览器,word/excell会直接下载
spring.resources.static-locations=classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/,file:${uploadPath}

上传接口

/**
 * 文件上传
 * @Author:sahana
 */
@RestController @Slf4j public class UploadController {

  @Value("${uploadPath}") String uploadPath;//上传文件的保存路径
  
  @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
      try {
        Path path = Paths.get(uploadPath, file.getOriginalFilename());//存储路径
        Files.copy(file.getInputStream(), path);//写入
         //       --另一种方式
         //        File serverFile = new File(uploadPath+file.getOriginalFilename());
         //        file.transferTo(serverFile);
        return "上传成功";
      } catch (IOException e) {
        return "上传失败";
      }
    } else {
      return "空文件";
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值