SpringBoot實(shí)現(xiàn)文件上傳并返回url鏈接的示例代碼
檢查依賴
確保pom.xml包含了Spring Boot Web的依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
創(chuàng)建Controller
創(chuàng)建公用上傳文件控制器
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 { // 構(gòu)建上傳目錄的路徑 String uploadDir = servletContext.getRealPath("/upload/test/"); // 確保目錄存在 File dirPath = new File(uploadDir); if (!dirPath.exists()) { dirPath.mkdirs(); } // 構(gòu)建上傳文件的完整路徑 Path path = Paths.get(uploadDir).resolve(file.getOriginalFilename()); System.out.println(path); // 保存文件 Files.write(path, file.getBytes()); // 構(gòu)建文件在Web應(yīng)用中的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為我本地封裝的統(tǒng)一返回格式的類
配置屬性
在application.properties或application.yml中,你可以配置一些與文件上傳相關(guān)的屬性,比如文件大小限制等。
# application.properties 示例 spring.servlet.multipart.max-file-size=128KB spring.servlet.multipart.max-request-size=10MB
驗(yàn)證
請求 /upload
路徑
文件會默認(rèn)放在系統(tǒng)的臨時(shí)文件目錄
到此這篇關(guān)于SpringBoot實(shí)現(xiàn)文件上傳并返回url鏈接的示例代碼的文章就介紹到這了,更多相關(guān)SpringBoot文件上傳并返回url內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot注解篇之@Resource與@Autowired的使用區(qū)別
@Resource 注解和 @Autowired 注解都是在 Spring Framework 中進(jìn)行依賴注入的注解,那么你知道他們有什么區(qū)別嗎,本文就來介紹一下2023-12-12windows 32位eclipse遠(yuǎn)程hadoop開發(fā)環(huán)境搭建
這篇文章主要介紹了windows 32位eclipse遠(yuǎn)程hadoop開發(fā)環(huán)境搭建的相關(guān)資料,需要的朋友可以參考下2016-07-07SpringBoot整合Guava Cache實(shí)現(xiàn)全局緩存的示例代碼
這篇文章主要介紹了SpringBoot整合Guava Cache實(shí)現(xiàn)全局緩存,Guava Cache是Google Guava庫中的一個模塊,提供了基于內(nèi)存的本地緩存實(shí)現(xiàn),文中介紹了SpringBoot整合使用Guava Cache的具體步驟,需要的朋友可以參考下2024-03-03mybatis教程之查詢緩存(一級緩存二級緩存和整合ehcache)
這篇文章主要介紹了mybatis教程之查詢緩存(一級緩存二級緩存和整合ehcache),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05