SpringBoot实现文件上传并返回url链接的示例代码
检查依赖
确保pom.xml包含了Spring Boot Web的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
创建Controller
创建公用上传文件控制器
package com.example.ruijisboot.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
public class FileUploadController {
@Autowired
private ServletContext servletContext;
@PostMapping("/upload")
public R handleFileUpload(MultipartFile file) {
System.out.println(file);
if (file.isEmpty()) {
// return "Please select a file to upload.";
return R.error("Please select a file to upload.");
}
try {
// 构建上传目录的路径
String uploadDir = servletContext.getRealPath("/upload/test/");
// 确保目录存在
File dirPath = new File(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
// 构建上传文件的完整路径
Path path = Paths.get(uploadDir).resolve(file.getOriginalFilename());
System.out.println(path);
// 保存文件
Files.write(path, file.getBytes());
// 构建文件在Web应用中的URL
String fileUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/upload/test/")
.path(file.getOriginalFilename())
.toUriString();
// return "File uploaded successfully! You can download it from: " + fileUrl;
return R.success(fileUrl,"成功");
} catch (IOException e) {
e.printStackTrace();
// return "File upload failed!";
return R.error("File upload failed!");
}
}
}
这里R为我本地封装的统一返回格式的类
配置属性
在application.properties或application.yml中,你可以配置一些与文件上传相关的属性,比如文件大小限制等。
# application.properties 示例 spring.servlet.multipart.max-file-size=128KB spring.servlet.multipart.max-request-size=10MB
验证
请求 /upload 路径

文件会默认放在系统的临时文件目录
到此这篇关于SpringBoot实现文件上传并返回url链接的示例代码的文章就介绍到这了,更多相关SpringBoot文件上传并返回url内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot注解篇之@Resource与@Autowired的使用区别
@Resource 注解和 @Autowired 注解都是在 Spring Framework 中进行依赖注入的注解,那么你知道他们有什么区别吗,本文就来介绍一下2023-12-12
windows 32位eclipse远程hadoop开发环境搭建
这篇文章主要介绍了windows 32位eclipse远程hadoop开发环境搭建的相关资料,需要的朋友可以参考下2016-07-07
SpringBoot整合Guava Cache实现全局缓存的示例代码
这篇文章主要介绍了SpringBoot整合Guava Cache实现全局缓存,Guava Cache是Google Guava库中的一个模块,提供了基于内存的本地缓存实现,文中介绍了SpringBoot整合使用Guava Cache的具体步骤,需要的朋友可以参考下2024-03-03
mybatis教程之查询缓存(一级缓存二级缓存和整合ehcache)
这篇文章主要介绍了mybatis教程之查询缓存(一级缓存二级缓存和整合ehcache),具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-05-05


最新评论