ASP.NET Web API 透過 MultipartFormDataStreamProvider 處理 multipart/form-data 上傳,搭配非同步 ReadAsMultipartAsync 可輕鬆實作圖片上傳端點。本文提供生產級範例,涵蓋檔案類型/大小驗證、唯一檔名產生、實體檔案搬移與結構化 JSON 回應。
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace DemoApi.Controllers
{
public class UploadController : ApiController
{
// POST api/upload/img
[HttpPost]
[Route("api/upload/img")]
public async Task<IHttpActionResult> UploadImage()
{
// 1. 驗證 Content-Type
if (!Request.Content.IsMimeMultipartContent("form-data"))
return Content(HttpStatusCode.UnsupportedMediaType,
new { error = 1, errmsg = "僅支援 multipart/form-data" });
// 2. 設定暫存目錄 (App_Data/Uploads/Temp)
string tempRoot = HttpContext.Current.Server.MapPath("~/App_Data/Uploads/Temp");
Directory.CreateDirectory(tempRoot);
var provider = new MultipartFormDataStreamProvider(tempRoot);
try
{
// 3. 非同步讀取多部分內容
await Request.Content.ReadAsMultipartAsync(provider);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
// 4. 取得第一個檔案 (單檔上傳情境)
var fileData = provider.FileData.FirstOrDefault();
if (fileData == null)
return Ok(new { error = 1, errmsg = "未收到檔案" });
// 5. 解析原始檔名 (移除雙引號)
string originalName = fileData.Headers.ContentDisposition.FileName.Trim('"');
FileInfo fileInfo = new FileInfo(fileData.LocalFileName);
// 6. 基本驗證
const long MaxBytes = 10 * 1024 * 1024; // 10 MB
if (fileInfo.Length == 0)
return Ok(new { error = 1, errmsg = "檔案為空" });
if (fileInfo.Length > MaxBytes)
return Ok(new { error = 1, errmsg = "檔案超過 10 MB 限制" });
string ext = Path.GetExtension(originalName).ToLowerInvariant();
string[] allowed = { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };
if (Array.IndexOf(allowed, ext) < 0)
return Ok(new { error = 1, errmsg = "不支援的副檔名" });
// 7. 產生唯一檔名:yyyyMMddHHmmss_ffff + 副檔名
string dateFolder = DateTime.Now.ToString("yyyyMMdd");
string finalDir = Path.Combine(tempRoot, dateFolder);
Directory.CreateDirectory(finalDir);
string uniqueName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff") + ext;
string finalPath = Path.Combine(finalDir, uniqueName);
// 8. 移動並清理暫存檔
fileInfo.MoveTo(finalPath); // 同磁碟區即為重命名,跨磁碟自動複製+刪除
// 9. 回傳成功資訊 (可擴充回傳相對 URL、寬高等)
string relativeUrl = $"/App_Data/Uploads/Temp/{dateFolder}/{uniqueName}";
return Ok(new
{
error = 0,
errmsg = "上傳成功",
url = relativeUrl,
size = fileInfo.Length,
name = uniqueName
});
}
}
}
<input type="file" id="fileInput" accept="image/*" />
<button id="btnUpload">上傳</button>
<div id="preview"></div>
<script>
$('#btnUpload').click(function () {
var file = $('#fileInput')[0].files[0];
if (!file) return alert('請選擇圖片');
var fd = new FormData();
fd.append('file', file); // key 需與後端 FileData 對應
$.ajax({
url: '/api/upload/img',
type: 'POST',
data: fd,
processData: false,
contentType: false,
success: function (res) {
if (res.error === 0) {
$('#preview').html($('<img>').attr('src', res.url).css('max-width', '300px'));
console.log('上傳成功', res);
} else {
alert(res.errmsg);
}
},
error: function (xhr) { alert('伺服器錯誤: ' + xhr.status); }
});
});
</script>
await ReadAsMultipartAsync、MoveTo 皆非阻塞,提升並發吞吐。Image.FromStream 驗證真實圖片格式。{ error: 0/1, errmsg: '', data: {} } 結構,前端統一處理。將 provider.FileData 迴圈處理,回傳陣列即可;前端 fd.append('files', file1); fd.append('files', file2); 並設定 input[multiple]。