1. 程式人生 > >Form提交圖片檢視並儲存

Form提交圖片檢視並儲存

View:

 <div id="container">        <form id="myForm" action="/Text/FromPost_1"  method="post" enctype="multipart/form-data">                <p class="img_P"><img id="previewPic" name="previewPic"style="width:100px;height:100px" /></p>               <p><input type="file" id="imgUpload" name="imgUpload" onclick="read()"/></p>               <p><button id="submitBtn" type="submit" value="提交">提交</button></p>             </form> </div>

<script>

//圖片瀏覽     function read() {         $('#imgUpload').on('change', function () {             var file = this.files[0];             if (this.files && file) {                 var reader = new FileReader();                 reader.onload = function (e) {                     $('#previewPic').attr('src', e.target.result);                 }                 reader.readAsDataURL(file);             }         })     } </script> Controller:

  public ActionResult FromPost_1()         {             if (Request.Files.Count > 0)             {                 string extension ="";                 HttpPostedFileBase file = Request.Files[0] as HttpPostedFileBase;                 if (file.FileName.Length > 0)                 {                     if (file.FileName.IndexOf('.') > -1)                     {                         //獲取副檔名            extension =file.FileName.Substring(file.FileName.LastIndexOf('.')+1, file.FileName.Length- file.FileName.LastIndexOf('.') -1).ToLower();                         if (extension=="gift"|| extension == "jpg")                         {                             string filePath = "/AA/Upload/";                             //建立路徑                             CreateFilePath(filePath);                             if (file.FileName.ToString() != "")                             {                                 string absoluteSavePath = System.Web.HttpContext.Current.Server.MapPath("~" + filePath);                                 var pathLast = Path.Combine(absoluteSavePath, file.FileName);                                 file.SaveAs(pathLast);                             }                         }                         else { return Content("Fail"); }                     }                 }             }             return Content("success");         }         public static void CreateFilePath(string savePath)         {             string Absolute_savePath = System.Web.HttpContext.Current.Server.MapPath("~" + savePath);             if (!Directory.Exists(Absolute_savePath))                 Directory.CreateDirectory(Absolute_savePath);         }

儲存圖片建議儲存在伺服器中的實體地址中,

如果要直接將圖片轉化為二進位制檔案流儲存在mysql中,那麼mysql負擔很重。而且解析圖片是可能會出現失真現象,這樣一來圖片可能解析不成功或圖片不清晰。

我們退一步講可以將圖片在服務端的地址存在在mysql中,這樣減少loading,效率變高