Spring Boot中保存前端上傳的圖片實(shí)現(xiàn)步驟詳解
在Spring Boot中保存前端上傳的圖片可以通過(guò)以下步驟實(shí)現(xiàn):
1. 添加依賴
確保在pom.xml中已包含Spring Web依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>2. 配置文件上傳限制
在application.properties中設(shè)置文件大小限制:
spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB #====自定義變量====== #文件上傳地址 file.upload.dir=uploads/
3. 創(chuàng)建文件上傳控制器
package com.hirain.mall.controller;
import com.hirain.mall.common.ApiRestResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;
@RestController
@RequestMapping("/images")
public class ImageController {
@Value("${file.upload.dir}") // 從配置文件中讀取路徑
private String uploadDir;
@PostMapping("/upload")
public ApiRestResponse<?> uploadImage(
@RequestParam("image") MultipartFile file,
HttpServletRequest request) {
try {
// 創(chuàng)建目錄 (如果不存在)
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
// 生成唯一文件名 (避免覆蓋)
String originalFileName = file.getOriginalFilename();
String fileExt = originalFileName.substring(originalFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID() + fileExt;
// 保存文件
Path targetPath = uploadPath.resolve(newFileName);
Files.copy(file.getInputStream(), targetPath);
// 生成訪問(wèn) URL (使用環(huán)境信息構(gòu)建完整URL)
String baseUrl = request.getRequestURL().toString().replace(request.getRequestURI(), "");
String imageUrl = baseUrl + "/images/" + newFileName;
return ApiRestResponse.success(Map.of(
"filename", newFileName,
"url", imageUrl//完成靜態(tài)資源映射配置后,通過(guò)瀏覽器直接訪問(wèn)該地址即可訪問(wèn)圖片
));
} catch (Exception e) {
return ApiRestResponse.error(500,"上傳失敗: " + e.getMessage());
}
}
}4.靜態(tài)資源映射配置類WebConfig
package com.hirain.mall.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.File;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${file.upload.dir}")
private String uploadDir;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 將真實(shí)的上傳目錄映射為虛擬路徑
registry.addResourceHandler("/images/**")
.addResourceLocations("file:" + uploadDir + File.separator);
}
}5. 前端調(diào)用示例(HTML)
<input type="file" id="imageInput">
<button onclick="uploadImage()">上傳</button>
<script>
async function uploadImage() {
const fileInput = document.getElementById('imageInput');
const formData = new FormData();
formData.append('image', fileInput.files[0]);
const response = await fetch('http://localhost:8080/images/upload', {
method: 'POST',
body: formData
});
const result = await response.text();
console.log(result);
}
</script>6. postman調(diào)用示例

關(guān)鍵點(diǎn)說(shuō)明:
文件保存路徑:
- 示例中使用相對(duì)路徑
uploads/(項(xiàng)目根目錄下) - 生產(chǎn)環(huán)境建議使用絕對(duì)路徑(如
/var/www/uploads/)
文件名處理:
- 使用時(shí)間戳前綴確保唯一性
- 保留原始文件名后綴(通過(guò)
file.getOriginalFilename()獲?。?/li>
異常處理:
- 捕獲
IOException處理文件操作異常 - 返回錯(cuò)誤信息給前端
添加文件類型校驗(yàn):
if (!file.getContentType().startsWith("image/")) {
return "僅支持圖片文件";
}添加安全限制:
- 限制文件擴(kuò)展名(jpg, png等)
- 使用病毒掃描工具掃描上傳文件
云存儲(chǔ)方案:
- 生產(chǎn)環(huán)境建議使用云存儲(chǔ)(AWS S3, 阿里云OSS等)
- 示例代碼替換為云存儲(chǔ)SDK的上傳邏輯
處理流程示意圖:

其中,前端上傳圖片后,后端保存在本地的流程如下:
前端 → 發(fā)送Multipart請(qǐng)求 → Spring控制器 → 驗(yàn)證文件 → 生成唯一文件名 → 保存到本地 → 返回結(jié)果
根據(jù)實(shí)際需求選擇本地存儲(chǔ)或云存儲(chǔ)方案,并注意做好文件類型校驗(yàn)和安全防護(hù)措施。
到此這篇關(guān)于Spring Boot中保存前端上傳的圖片的文章就介紹到這了,更多相關(guān)Spring Boot前端上傳圖片內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot實(shí)戰(zhàn)之SSL配置詳解
今天小編就為大家分享一篇關(guān)于SpringBoot實(shí)戰(zhàn)之SSL配置詳解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-02-02
Java 的 Condition 接口與等待通知機(jī)制詳解
在 Java 并發(fā)編程里,實(shí)現(xiàn)線程間的協(xié)作與同步是極為關(guān)鍵的任務(wù),本文將深入探究Condition接口及其背后的等待通知機(jī)制,感興趣的朋友一起看看吧2025-05-05
java實(shí)現(xiàn)遺傳算法實(shí)例分享(打印城市信息)
本文介紹java實(shí)現(xiàn)遺傳算法的實(shí)例,代碼中使用城市名做為數(shù)據(jù),可以打印當(dāng)前代數(shù)的所有城市序列,以及其相關(guān)的參數(shù),大家參考使用吧2014-01-01
Maven的使用和配置國(guó)內(nèi)源的保姆級(jí)教程
Maven是?個(gè)項(xiàng)目管理工具,基于POM(Project Object Model,項(xiàng)目對(duì)象模型)的概念,Maven可以通過(guò)一小段描述信息來(lái)管理項(xiàng)目的構(gòu)建,報(bào)告和文檔的項(xiàng)目管理工具軟件,很多新手還不夠了解maven,所以本文給大家講解Maven的使用和配置,需要的朋友可以參考下2025-04-04

