SpringBoot实现文件上传并返回url链接的示例代码
作者:mr_cmx
文件上传,当我们选择了某一个图片文件之后,这个文件就会上传到服务器,从而完成文件上传的操作,是指将本地图片、视频、音频等文件上传到服务器,供其他用户浏览或下载的过程,本文给大家介绍了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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
