以下是前端上传图片到后端 SpringBoot,并允许访问图片的完整实现步骤:
1. 后端 SpringBoot 实现
(1)添加依赖
确保 pom.xml 包含文件处理和 Web 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
(2)配置文件存储路径
在 application.properties 中配置:
# 文件存储路径(按需修改)
file.upload-dir=./uploads/
# 允许访问静态资源
spring.mvc.static-path-pattern=/images/**
spring.web.resources.static-locations=file:${file.upload-dir}
(3)编写上传接口
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
@RequestMapping("/api")
public class FileUploadController {
@Value("${file.upload-dir}")
private String uploadDir;
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 创建目录(如果不存在)
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
// 保存文件到本地
Path filePath = uploadPath.resolve(file.getOriginalFilename());
file.transferTo(filePath);
return ResponseEntity.ok("文件上传成功: " + file.getOriginalFilename());
} catch (IOException e) {
return ResponseEntity.internalServerError().body("上传失败: " + e.getMessage());
}
}
}
(4)启用静态资源访问
SpringBoot 默认会映射 static 和 public 目录,但自定义路径需通过配置类显式添加:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/images/**")
.addResourceLocations("file:uploads/"); // 与配置中的路径一致
}
}
2. 前端实现(HTML + JavaScript)
使用 <input type="file"> + Fetch API 上传:
<input type="file" id="imageInput" accept="image/*">
<button onclick="uploadImage()">上传图片</button>
<script>
async function uploadImage() {
const fileInput = document.getElementById('imageInput');
const file = fileInput.files[0];
if (!file) {
alert('请选择图片!');
return;
}
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('http://localhost:8080/api/upload', {
method: 'POST',
body: formData,
});
if (response.ok) {
const result = await response.text();
alert(result);
// 显示上传的图片(假设文件名不变)
const imageUrl = `http://localhost:8080/images/${file.name}`;
console.log('访问链接:', imageUrl);
// 动态创建图片预览(可选)
const imgPreview = document.createElement('img');
imgPreview.src = imageUrl;
document.body.appendChild(imgPreview);
} else {
throw new Error('上传失败');
}
} catch (error) {
console.error('Error:', error);
alert('上传异常!');
}
}
</script>
3. 测试流程
- 上传文件:选择图片并点击按钮,文件将保存到后端的
./uploads/目录。 - 访问图片:通过 URL
http://localhost:8080/images/文件名直接访问。
常见问题解决
- 403 Forbidden:检查文件权限或静态资源配置路径是否正确。
- 404 Not Found:确保文件已成功保存,且路径匹配。
- 跨域问题:若前后端分离开发,需在后端添加
@CrossOrigin注解。
如果需要更复杂的功能(如缩略图生成、数据库记录),可以进一步扩展代码。
内容由零声教学AI助手提供,问题来源于学员提问




