WinForm (Client) → HTTP POST (multipart/form-data) → Java Server (Spring MVC / Servlet) → 文件存儲
using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
{
// 文件流
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
content.Add(fileContent, "file", Path.GetFileName(filePath));
// 可選:其他元數據
content.Add(new StringContent("video"), "type");
var response = await client.PostAsync("https://server:8080/api/upload", content);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
}
或簡單同步版 (WebClient):
using (var wc = new WebClient())
{
byte[] resp = wc.UploadFile("https://server:8080/api/upload", "POST", filePath);
// 處理響應
}
@PostMapping("/api/upload")
public ResponseEntity upload(@RequestParam("file") MultipartFile file,
@RequestParam("type") String type) {
if (file.isEmpty()) return ResponseEntity.badRequest().body("文件為空");
String destPath = "/data/uploads/" + UUID.randomUUID() + "_" + file.getOriginalFilename();
file.transferTo(Paths.get(destPath));
// 保存元數據到數據庫...
return ResponseEntity.ok("上傳成功: " + destPath);
}
HttpClient 流式寫入避免 OOM。client.Timeout = TimeSpan.FromMinutes(30)。Path.Combine / Paths.get。