Spring Boot中保存前端上傳的圖片實(shí)現(xiàn)步驟詳解
在Spring Boot中保存前端上傳的圖片可以通過以下步驟實(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);
// 生成訪問 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)資源映射配置后,通過瀏覽器直接訪問該地址即可訪問圖片
));
} 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)說明:
文件保存路徑:
- 示例中使用相對(duì)路徑
uploads/(項(xiàng)目根目錄下) - 生產(chǎn)環(huán)境建議使用絕對(duì)路徑(如
/var/www/uploads/)
文件名處理:
- 使用時(shí)間戳前綴確保唯一性
- 保留原始文件名后綴(通過
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)文章
java題解Leetcode 8字符串轉(zhuǎn)換整數(shù)
這篇文章主要為大家介紹了java題解Leetcode 8字符串轉(zhuǎn)換整數(shù)實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
Java使用split分割無效獲取不到預(yù)期效果的解決辦法
這篇文章主要給大家介紹了關(guān)于Java使用split分割無效獲取不到預(yù)期效果的解決辦法,java的String類中有個(gè)split方法,這個(gè)是我們經(jīng)常使用到的,需要的朋友可以參考下2023-08-08
Java如何按16進(jìn)制發(fā)送和接收TCP指令
這篇文章主要介紹了Java如何按16進(jìn)制發(fā)送和接收TCP指令問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
Spring中ImportBeanDefinitionRegistrar源碼和使用方式
Spring容器擴(kuò)展流程總結(jié):1. 定義Mapper層,2. 通過FactoryBean創(chuàng)建代理對(duì)象,3. 使用ImportBeanDefinitionRegistrar修改Bean定義,4. 應(yīng)用自定義注解@LuoyanImportBeanDefinitionRegistrar,5. 配置類中執(zhí)行后置處理器,6. 啟動(dòng)類中查看源碼,希望對(duì)大家有所幫助2024-11-11
SpringBoot遇到的坑@Qualifier報(bào)紅的解決
這篇文章主要介紹了SpringBoot遇到的坑@Qualifier報(bào)紅的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
SpringBoot中@RestControllerAdvice注解的使用
這篇文章主要介紹了SpringBoot中@RestControllerAdvice注解的使用,@RestControllerAdvice主要用精簡(jiǎn)客戶端返回異常,它可以捕獲各種異常,需要的朋友可以參考下2024-01-01
SpringCloud中分析講解Feign組件添加請(qǐng)求頭有哪些坑梳理
在spring?cloud的項(xiàng)目中用到了feign組件,簡(jiǎn)單配置過后即可完成請(qǐng)求的調(diào)用。又因?yàn)橛邢蛘?qǐng)求添加Header頭的需求,查閱了官方示例后,就覺得很簡(jiǎn)單,然后一頓操作之后調(diào)試報(bào)錯(cuò)...下面我們來詳細(xì)了解2022-06-06

