1. 程式人生 > 其它 >ASP.NET MVC 壹:瀏覽器選擇檔案並上傳到伺服器

ASP.NET MVC 壹:瀏覽器選擇檔案並上傳到伺服器

  1. 目的:在網頁上選擇需要的檔案,並上傳到IIS Express伺服器。
  2. 檔案結構:
  3. Upload/Index.cshtml程式碼
     1 @using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
     2 {
     3     <div style="margin-top: 20px;">
     4         <fieldset id="myfieldset1">
     5             <legend>資訊匯入</legend>
     6
    <p>選擇Excel檔案:<input id="FileUpload" type="file" name="files" style="width: 250px; height: 24px;background: White" class="easyui-validatebox" /></p> 7 <p><input id="btnImport" type="submit" value="匯入" style="width: 60px; height: 28px;" /></p> 8
    <p style="color: Red; text-align: center;">@ViewBag.error</p> 9 </fieldset> 10 </div> 11 }
    ./Upload/Index.cshtml
  4. Upload/Upload程式碼
     1 public ActionResult Upload(HttpPostedFileBase httpPostedFileBase)
     2         {
     3             HttpPostedFileBase httpPostedFile = Request.Files["
    files"]; 4 string FileName, SavePath; 5 if(httpPostedFile == null || httpPostedFile.ContentLength <= 0) 6 { 7 ViewBag.error = "檔案不能為空"; 8 return View(); 9 } 10 else 11 { 12 string ExcelName = Path.GetFileName(httpPostedFile.FileName); 13 string Extention = System.IO.Path.GetExtension(ExcelName); 14 string NoExtention = Path.GetFileNameWithoutExtension(ExcelName); 15 string FileType = ".xlsx"; 16 FileName = NoExtention + Extention; 17 if (!FileType.Contains(Extention)) 18 { 19 ViewBag.error = "只能匯入xlsx格式的檔案"; 20 return View(); 21 } 22 string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/"; 23 SavePath = Path.Combine(path, FileName); 24 httpPostedFile.SaveAs(SavePath); 25 } 26 string Result = string.Empty; 27 string strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + SavePath + ";" + "Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; 28 OleDbConnection oleDbConnection = new OleDbConnection(strConn); 29 oleDbConnection.Open(); 30 OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter("select * from [生產計劃$]", strConn); 31 DataSet dataSet = new DataSet(); 32 try 33 { 34 oleDbDataAdapter.Fill(dataSet, "Results"); 35 oleDbConnection.Close(); 36 DataTable dataTable = dataSet.Tables["Results"]; 37 } 38 catch(InvalidCastException e) 39 { 40 41 } 42 SprayTable = dataSet.Tables["Results"].DefaultView.ToTable(); 43 //將部件資料放到資料庫裡 44 //Spray spray = new Spray(); 45 //for(int i = 0; i < SprayTable.Rows.Count; i++) 46 //{ 47 // spray.MaterialGroupNum = SprayTable.Rows[i][20].ToString(); 48 // spray.MaterialName = SprayTable.Rows[i][7].ToString().Replace("(", "(").Replace(")", ")");//不管用 49 // spray.PlanNum = Convert.ToInt32(SprayTable.Rows[i][12].ToString()); 50 // layuiContext.Sprays.Add(spray); 51 // layuiContext.SaveChanges(); 52 //} 53 return View(SprayTable); //將excel表裡的資料儲存到了SprayTable裡。 54 }
    ./Controllers/UploadController.cs