實現思路大概分為兩步:
1. 通過上傳接口,將圖片上傳到服務器,返回文件路徑給客戶端;
2. 點擊保存上傳,將文件路徑保存到數據庫,如果是多張圖片,路徑用逗號分隔。
核心上傳代碼:
/// <summary>
/// 圖片上傳
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("PostFile")]
public HttpResponseMessage PostFile()
{
//TODO:Save file...
if (!Request.Content.IsMimeMultipartContent("form-data"))
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
HttpResponseMessage response = null;
HttpContext context = HttpContext.Current;
try
{
HttpPostedFile file = HttpContext.Current.Request.Files["form-data"];
if (!string.IsNullOrEmpty(context.Request["type"]))
{
string type = context.Request["type"].ToString();
if (type == "image")
{
if (!string.IsNullOrEmpty(context.Request["size"]))
{
string sizes = context.Request["size"].ToString();
response = Request.CreateResponse(HttpStatusCode.Accepted, SaveBySize(file, sizes.Split(',')));
}
else
{
context.Response.Write("{ret:-1,msg:\"參數錯誤\"}");
}
}
else
{
response = Request.CreateResponse(HttpStatusCode.Accepted, Save(file));
}
}
else
{
response = Request.CreateResponse(HttpStatusCode.Accepted, Save(file));
}
}
catch (HttpResponseException ex)
{
//throw new HttpResponseException(HttpStatusCode.BadRequest);
response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, ex.ToString());
}
return response;
}
實現效果

點擊選擇圖片

點擊確定上傳

圖片預覽

有需要的朋友可以掃描下方二維碼加入QQ群,我會把源碼分享在QQ群里

