当前位置: 首页 > news >正文

Spring Boot中保存前端上传的图片 - 教程

在Spring Boot中保存前端上传的图片可以通过以下步骤实现:

1. 添加依赖

确保在pom.xml中已包含Spring Web依赖:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. 配置文件上传限制

application.properties中设置文件大小限制:

spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
#====自定义变量======
#文件上传地址
file.upload.dir=uploads/

3. 创建文件上传控制器

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 {
// 创建目录 (如果不存在)
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 (使用环境信息构建完整URL)
String baseUrl = request.getRequestURL(
).toString(
).replace(request.getRequestURI(
)
, ""
)
;
String imageUrl = baseUrl + "/images/" + newFileName;
return ApiRestResponse.success(Map.of(
"filename"
, newFileName,
"url"
, imageUrl//完成静态资源映射配置后,通过浏览器直接访问该地址即可访问图片
)
)
;
}
catch (Exception e) {
return ApiRestResponse.error(500
,"上传失败: " + e.getMessage(
)
)
;
}
}
}

4.静态资源映射配置类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) {
// 将真实的上传目录映射为虚拟路径
registry.addResourceHandler("/images/**"
)
.addResourceLocations("file:" + uploadDir + File.separator)
;
}
}

5. 前端调用示例(HTML)

<input type="file" id="imageInput"><button onclick="uploadImage(
)">上传</button>
<script>asyncfunction 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调用示例

在这里插入图片描述

关键点说明:

  1. 文件保存路径

  2. 文件名处理

  3. 异常处理

进阶优化建议:

  1. 添加文件类型校验

    if (!file.getContentType(
    ).startsWith("image/"
    )
    ) {
    return "仅支持图片文件"
    ;
    }
  2. 添加安全限制

  3. 云存储方案

处理流程示意图:

在这里插入图片描述
其中,前端上传图片后,后端保存在本地的流程如下:

前端 → 发送Multipart请求 → Spring控制器 → 验证文件 → 生成唯一文件名 → 保存到本地 → 返回结果

根据实际需求选择本地存储或云存储方案,并注意做好文件类型校验和安全防护措施。

http://www.hskmm.com/?act=detail&tid=25285

相关文章:

  • P2724 [IOI 1998 / USACO3.1] 联系 Contact 做题笔记
  • 深入解析:Linux运维笔记:服务器感染 netools 病毒案例
  • 设计模式——命令设计模式(行为型) - 详解
  • 港专专利申请量被反超,背后是谁在“偷家”?
  • 版权诉讼下的MiniMax:AI独角兽的上市迷途
  • HTB Eureka靶机渗透实战 - Spring Boot堆转储与Bash算术注入漏洞利用
  • 手机照片太多了存哪里? - 实践
  • 时隔十六年的南京之旅
  • 高贵的北上广深,没有父母托举,90后很难成家
  • 使用AI图像服务规模化视觉内容生产
  • 实用指南:基于贝叶斯优化神经网络的光伏功率预测综述
  • 详细介绍:ROS2与Unitree机器人集成指南
  • 布尔类型
  • 安装iTrustSSL证书 去除此网站不支持安全连接提示
  • 2025钻机厂家最新推荐榜:岩芯钻机,勘探钻机,地质钻机,取样钻机,空气反循环钻机公司推荐
  • 在AI技术快速实现创意的时代,挖掘游戏开发框架新需求成为关键
  • iNaturalist开放自然数据与计算机视觉挑战
  • macOS 编辑字幕
  • reLeetCode 热题 100- 438. 找到字符串中所有字母异位词 - MKT
  • Flutter 251006
  • [MCP] Register Prompt
  • [Node.js] Server-Sent Events
  • day1 Gitlab Runner 学习
  • Software Foundations Vol.I : 使用结构化的数据(Lists)
  • Software Foundations Vol.I : 归纳证明(Induction)
  • Software Foundations Vol.I : Coq函数式编程(Basics)
  • Python 在自然语言处理中的应用与发展
  • Python 在网络爬虫与数据采集中的应用
  • 15_spring_data_neo4j简单教程
  • CF2152G Query Jungle(线段树,重链剖分,*)