Spring Boot实现图片上传至resource静态资源文件夹

在Spring Boot项目中,我们经常需要将用户上传的图片或其他文件保存到服务器的特定位置。Spring Boot默认将静态资源文件存放在`src/main/resources/static`目录下,而`src/main/resources/public`目录则用于存放公共资源。本文将介绍如何将前端上传的图片保存到`src/main/resources/static`目录下。

首先,确保你的Spring Boot项目中已经包含了`spring-boot-starter-web`依赖,它提供了处理HTTP请求和响应所需的基础功能。

接下来,我们需要创建一个控制器来处理文件上传请求。以下是一个简单的控制器示例:

java

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.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.UUID;

@RestController

@RequestMapping("/upload")

public class FileUploadController {

@PostMapping("/image")

public String handleFileUpload(@RequestParam("file") MultipartFile file) {

String fileName = UUID.randomUUID().toString() + file.getOriginalFilename();

String filePath = "static/images/" + fileName;

try {

// 将文件保存到指定的路径

File newFile = new File(filePath);

file.transferTo(newFile);

// 返回成功信息

return "File uploaded successfully!";

} catch (IOException e) {

// 处理文件上传异常

e.printStackTrace();

return "Error uploading file!";

}

}

}

在这个控制器中,我们定义了一个`handleFileUpload`方法,它接受一个`MultipartFile`类型的参数,这是Spring MVC提供的用于处理多部分请求体的接口。我们使用`UUID`生成一个唯一的文件名,并将文件保存到`static/images/`目录下。

确保在`application.properties`或`application.yml`文件中配置了静态资源的路径:

properties

# application.properties

spring.mvc.static-path-pattern=/static/**

或者

yaml

# application.yml

spring:

mvc:

static-path-pattern: /static/**

这样配置后,Spring Boot会识别`/static`路径下的资源,并将其映射到`src/main/resources/static`目录下。

最后,在前端页面上,你可以使用`

`标签和``元素来上传图片,并通过AJAX请求将文件发送到Spring Boot后端。

html

转载请注明出处:https://www.wanxiangsucai.com/read/cv183920

话题推荐: ##