ASP.NET WebApi 圖片上傳
遇到的問題(基於Web服務前後端分離開發):
(1)服務端通過檔案流的形式把圖片上傳至伺服器指定的資料夾下,但是部署以後卻不能實現圖片上傳。
解決的方法:
(2)主要原因沒有理解Web專案的本質:
瀏覽器相當於客戶端,當客戶端向伺服器端提交上傳檔案時(注意:基於前後端分離開發,客戶端呼叫遠端服務上傳圖片和檔案),被上傳的檔案路徑雖然提交到了伺服器端,但是伺服器端的磁碟上通過被上傳的檔案路徑是檢測不到該圖片的存在的,因此在進行File.Exists(filePath)是檢測不到的。最終通過Form表單提交值伺服器端,實現圖片上傳值伺服器指定資料夾下。(小白再次記錄學習的過程...)
以下是程式碼的實現過程:
<form id="UpPicture" enctype="multipart/form-data" action="伺服器路徑地址" method="post">
<table>
<tr>
<td>工號</td>
<td>
<input type="type" name="Emp_Id" />
<input type="type" name="Cer_Id" />
<input type="file" name="Picture"/>
</td>
</tr>
<tr>
<td>提交</td>
<td>
<input type="submit" value="提交" /></td>
</tr>
</table>
</form>
伺服器端是實現:
/// <summary>
/// 新頭像上傳方法,客戶端通過表單的形式上傳
/// </summary>
/// <param name="emp_id">員工id</param>
/// <param name="cer_id">證書記錄id</param>
/// <returns></returns>
[HttpPost, Route("upload/picture")]
public IHttpActionResult NewPictureUpload()
{
//首先獲客戶端表單傳遞過來的Form資料
string _empId = HttpContext.Current.Request.Form["Emp_Id"];
string _cerId = HttpContext.Current.Request.Form["Cer_Id"];
//接收表單傳遞過來的圖片,需要限定上傳的圖片格式:".JPG", ".JPEG", ".GIF", ".PNG", ".BMP"
var file = HttpContext.Current.Request.Files["Picture"];
//首先判斷表單中的員工id和證書記錄是否為空,為空則限制客戶從客戶端上傳圖片,因為即使上傳成功也對應不到記錄
if (!string.IsNullOrWhiteSpace(_empId) && !string.IsNullOrWhiteSpace(_cerId))
{
//檢查檔案是否被預覽選中,判斷方式:通過判斷檔名是否為空或者空字串
if (!string.IsNullOrWhiteSpace(file.FileName))
{
//限定上傳圖片的格式型別
string[] LimitPictureType = { ".JPG", ".JPEG", ".GIF", ".PNG", ".BMP" };
//當圖片上被選中時,拿到檔案的副檔名
string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper();
//此處對圖片上傳的型別進行限定操作
if (LimitPictureType.Contains(currentPictureExtension))
{
//此處標記圖片上傳至伺服器的唯一新名稱
string _newFileName = Guid.NewGuid().ToString();
string _toServerPicturePath = DateTime.Now.Year + "/" + DateTime.Now.Month + "/";
string _dbPicturePath = "Certifications/" + _toServerPicturePath + _newFileName + currentPictureExtension;
_toServerPicturePath = AppDomain.CurrentDomain.BaseDirectory + "Certifications/" + _toServerPicturePath;//最終生成的檔名:+_newFileName +currentPictureExtension
//首先判斷圖片上傳至服務的路徑是否存在,不存在則建立並執行儲存操作,存在則直接儲存
if (Directory.Exists(_toServerPicturePath))
{
//最終上傳的檔案路徑全名
_toServerPicturePath = _toServerPicturePath + _newFileName + currentPictureExtension;
}
else
{//不存在此路徑,則建立後執行儲存操作
Directory.CreateDirectory(_toServerPicturePath);
_toServerPicturePath = _toServerPicturePath + _newFileName + currentPictureExtension;
}
//執行儲存圖片,並插入資料庫操作
file.SaveAs(HttpContext.Current.Server.MapPath("~/" + _dbPicturePath));
////執行資料庫相關操作,沒有異常則程式碼繼續執行,否則跳出
bflag = true;
msg = "圖片上傳操作成功!";
}
else
{
msg = "圖片上傳操作失敗,請選擇副檔名為:.JPG, .JPEG, .GIF, .PNG, .BMP 等型別圖片。";
}
}
else
{
msg = "圖片上傳操作失敗,圖片沒有被選中!";
}
}
else
{
msg = "圖片上傳操作失敗,請檢查記錄是否被選中!";
}
return MyJson(new { flag = bflag, msg = msg });
}