在Spring Boot中,可以通過以下步驟實現圖片上傳:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@RestController
public class ImageUploadController {
@Value("${upload-dir}")
private String uploadDir;
@PostMapping("/upload")
public ResponseEntity<String> uploadImage(@RequestParam("image") MultipartFile image) {
File file = new File(uploadDir + "/" + image.getOriginalFilename());
try {
image.transferTo(file);
return ResponseEntity.ok("Image uploaded successfully");
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload image");
}
}
}
upload-dir=/path/to/upload/directory
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
</head>
<body>
<h1>Upload Image</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
</body>
</html>
通過以上步驟,就可以實現在Spring Boot應用中上傳圖片的功能。在上傳圖片之前,確保文件上傳目錄的權限設置正確,并且確保文件上傳目錄存在。