返回

图片上传神器Spring Boot,带你轻松实现文件处理!

后端

使用 Spring Boot 实现图片上传和展示

1. 前端准备

首先,我们需要在前端创建一个 HTML 页面,用于上传和展示图片:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
  </form>
  <div id="image-container"></div>
</body>
</html>

2. Spring Boot 后端搭建

在 Spring Boot 后端,添加如下依赖:

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

并在 application.properties 中配置图片上传的保存目录:

spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

3. 处理图片上传

@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
  // 保存图片到指定目录
  String fileName = file.getOriginalFilename();
  Path filePath = Paths.get("/path/to/directory", fileName);
  Files.write(filePath, file.getBytes());
  // 返回成功信息
  return "success";
}

4. 展示图片

@GetMapping("/image/{fileName}")
public ResponseEntity<byte[]> getImage(@PathVariable String fileName) {
  // 读取图片文件
  Path filePath = Paths.get("/path/to/directory", fileName);
  byte[] imageBytes = Files.readAllBytes(filePath);
  // 设置响应头
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.IMAGE_JPEG);
  // 返回图片文件
  return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
}

5. 运行项目

运行 Spring Boot 项目,在浏览器中打开 HTML 页面即可体验图片上传和展示。

常见问题解答

1. 如何限制上传文件的大小?

application.properties 中配置 spring.servlet.multipart.max-file-size

2. 如何更改图片保存目录?

application.properties 中配置 spring.servlet.multipart.location

3. 如何处理上传失败?

handleFileUpload 方法中捕获异常并返回错误信息。

4. 如何支持多种图片格式?

getImage 方法中设置 MediaType 以支持多种格式。

5. 如何优化图片上传性能?

使用异步上传或分片上传技术。