使用Post圖片上傳至後端一些方法整理
1.使用HttpPostedFileBase類別
2.檢查圖片格式
3.根目錄(取得RequestUrl)(https://ithelp.ithome.com.tw/articles/10211054)
public ActionResult ReadBarcode(IEnumerable<HttpPostedFileBase> files)
{
if (files.Count() > 1)
{
foreach (var file in files)
{
if (file != null)
{
var fileName = $"{Path.GetFileName(file.FileName)}";
var path = Path.Combine(Server.MapPath($"~/File/TheOldSchoolArt"), fileName);
//副檔名
string ext = file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
file.SaveAs(path);
}
}
}
return View();
}
/// <summary>
/// 檢查上傳檔案是否為圖片格式
/// </summary>
/// <param name="fileName">完整檔案名稱</param>
/// <returns>True or False</returns>
public static bool CheckPhotoFormat(string fileName)
{
bool flag = false;
string fileExtension = Path.GetExtension(fileName).ToLower();
string[] allowedExtensions = { ".jpg", ".jpeg", ".png", ".gif" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (allowedExtensions[i].ToString().Equals(fileExtension))
{
flag = true;
}
}
return flag;
}
/// <summary>
/// 取得RequestUrl()
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string GetImageRequestAbsoluteUriPath(string fileName,string somePath)
{
var requestAbsoluteUri = $"{HttpContext.Current.Request.Url.Scheme}://{HttpContext.Current.Request.Url.Authority}{somePath}{fileName}";
return requestAbsoluteUri;
}