[HttpPost]
public ActionResult Uploads(HttpPostedFileBase file)
{
//判斷是否有上傳檔案
if (Request.Files["file"].ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(file.FileName);
string fileSavedPath = WebConfigurationManager.AppSettings["UploadPath"];
//判斷是否為excel檔
if (extension == ".xls" || extension == ".xlsx")
{
//更改檔名為當天日期時間
string newFileName = string.Concat(
DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"),
Path.GetExtension(file.FileName).ToLower());
fullFilePath = Path.Combine(Server.MapPath(fileSavedPath), newFileName);
// 存放檔案到伺服器上
Request.Files["file"].SaveAs(fullFilePath);
//將資料傳送到前端顯示
ViewBag.path = fullFilePath;
Response.Write("<script language=javascript>alert(' 檔案上傳成功 ');</" +
"script>");
}
else
{
Response.Write("<script language=javascript>alert('請上傳 .xls 或 .xlsx 格式的檔
案');</" + "script>");
}
}
else
{
Response.Write("<script language=javascript>alert('請選擇檔案');</" + "script>");
}
return View("ExcelImport");
}
<!--點選上傳檔案按鈕後POST到後端的Uploads的Action-->
@using (Html.BeginForm("Uploads", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="uploads">
<input type="file" id="upload_file" name="file" />
<button type="submit" id="upload_button" class="btn btn-primary">上傳檔案</button>
</div>
}
<div class="remote_file_path">
<label class="remote_file_path_label ">Remote File Path:</label>
<span class="form-control" id="remote_file_path">@ViewBag.path</span>
</div>
接著開啟網頁點擊選擇檔案,就會出現瀏覽資料本機的彈跳視窗
選擇好Excel檔案後點擊上傳檔案後,將會出現檔案上傳成功的彈跳視窗且也會顯示檔案的上傳路徑
最後到路徑中的資料夾將會看到多新增了一筆Excel檔案上來,完成檔案上傳的功能