最近因爲項目需要! 圖片上傳 功能
查了很多資料,瞭解到 <input type="file" style="width: 250px; "> 圖片只能進行form提交上傳保存! 不能使用ajax 進行保存。圖片上傳後的預覽效果! 沒找到合適的解決辦法
俺們只能用比較保守的方法使用 上傳在本地後在進行顯示!
後臺進行保存上傳的圖片 代碼如下
HttpPostedFileBase uploadFile= Request.Files[0]; //得到文件
string fileName = uploadFile.FileName;
string KZ = Path.GetExtension(fileName).ToLower();
string path = "";
if (!(KZ == ".png" || KZ == ".gif" || KZ == ".jpg" || KZ == ".jpeg"))
{
return Json("圖片文件格式錯誤!", JsonRequestBehavior.AllowGet);
}
else
{
Random r = new Random();
LogoFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + r.Next(100000, 999999) + "Logo" + KZ;
string directoryPath = Server.MapPath("~/Content/File/Images/");
if (!Directory.Exists(directoryPath))//不存在這個文件夾就創建這個文件夾
{
Directory.CreateDirectory(Server.MapPath("~/Content/File/Images/"));
}
path = Server.MapPath("~/Content/File/Images/") + LogoFileName;
uploadFile.SaveAs(path);
}