SpringBoot实现文件上传并返回url链接的示例代码
目录
- 检查依赖
- 创建Controller
- 配置属php性
- 验证
检查依赖
确保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.servle编程客栈t.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()) { www.devze.com 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(); /js/ 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内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
精彩评论