```java
/**
* 嘗試繪圖
*/
@GetMapping("/img/")
public ResponseEntity<byte[]> draw(@PathVariable("width") int width, @PathVariable("height") int height) throws IOException, Exception {
// Convert the BufferedImage to a byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// some code ...
ImageIO.write(image.appendRow(img1, img2, img3), "png", baos);
byte[] bytes = baos.toByteArray();
// Create and return a ResponseEntity with the image byte array and the appropriate headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
// headers.setContentType(MediaType.IMAGE_JPEG);
headers.setContentLength(bytes.length);
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
}
```
以下是使用 Spring Boot 製作一個 **接收圖片上傳的 POST API** 範例,可接收單張圖片並儲存到本地磁碟中。
---
## ✅ 1. Controller:上傳圖片的 API
```java
@RestController
@RequestMapping("/api/upload")
public class ImageUploadController {
private static final String UPLOAD_DIR = "uploads/";
@PostMapping
public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("No file selected");
}
try {
// 建立上傳資料夾(若不存在)
File uploadDir = new File(UPLOAD_DIR);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
// 儲存檔案
String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
Path filePath = Paths.get(UPLOAD_DIR, fileName);
file.transferTo(filePath);
return ResponseEntity.ok("File uploaded successfully: " + fileName);
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Failed to upload file");
}
}
}
```
---
## ✅ 2. Application 主程式需要這段設定(啟用檔案上傳)
```java
@SpringBootApplication
public class ImageUploadApplication {
public static void main(String[] args) {
SpringApplication.run(ImageUploadApplication.class, args);
}
}
```
---
## ✅ 3. application.properties 設定(非必需,但建議)
```properties
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB
```
---
## 🧪 測試方式(用 Postman)
* 方法:`POST`
* URL:`http://localhost:8080/api/upload`
* Body:
* 選擇 `form-data`
* key 為 `file`(型態選擇「File」)
* value 為選擇的圖片檔案
---
## 📁 檔案會儲存到哪?
上傳的檔案會被儲存在專案的 `/uploads` 資料夾中。如果你要儲存到其他位置,可以修改 `UPLOAD_DIR` 常數。
---
如果你想進一步把圖片存在資料庫、回傳下載連結、或用 Base64 處理,也可以告訴我,我可以提供對應範例。需要嗎?