本文將簡單介紹如何製作 Web API 接收前端上傳圖片,並調整圖片檔名及尺寸,用於用戶大頭貼圖片。
[HttpPost]
public async Task<IHttpActionResult> UploadProfile()
{
// 檢查請求是否包含 multipart/form-data.
if (!Request.Content.IsMimeMultipartContent()) {
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
// 檢查資料夾是否存在,若無則建立
string root = HttpContext.Current.Server.MapPath("~/upload/profile");
if (!Directory.Exists(root)) {
Directory.CreateDirectory("~/upload/profile");
}
try {
// 讀取 MIME 資料
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
// 取得檔案副檔名,單檔用.FirstOrDefault()直接取出,多檔需用迴圈
string fileNameData = provider.Contents.FirstOrDefault().Headers.ContentDisposition.FileName.Trim('\"');
string fileType = fileNameData.Remove(0, fileNameData.LastIndexOf('.')); // .jpg
// 定義檔案名稱
string fileName = "UserName" + "Profile" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileType;
// 儲存圖片,單檔用.FirstOrDefault()直接取出,多檔需用迴圈
var fileBytes = await provider.Contents.FirstOrDefault().ReadAsByteArrayAsync();
var outputPath = Path.Combine(root, fileName);
using (var output = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) {
await output.WriteAsync(fileBytes, 0, fileBytes.Length);
}
// 使用 SixLabors.ImageSharp 調整圖片尺寸 (正方形大頭貼)
var image = SixLabors.ImageSharp.Image.Load<Rgba32>(outputPath);
image.Mutate(x => x.Resize(120, 120)); // 輸入(120, 0)會保持比例出現黑邊
image.Save(outputPath);
return Ok(new
{
Status = true,
Data = new
{
FileName = fileName
}
});
}
catch (Exception e) {
return BadRequest(e.Message); // 400
}
}