iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 13
0
自我挑戰組

ArasPLM開發分享系列 第 13

[Day13]MVC檔案上傳

今天會介紹如何在MVC中上傳檔案到本機端,在前端畫面中顯示出上傳路徑,以及檔案類型的上傳卡控,這邊卡控的對象為Excel檔案(.xls/.xlsx)

Controller

  1. 首先先在Controller中建立一個具有HttpPost的Action,引數為接收前端view的file傳送過來的檔案,if判斷副檔名是否為Excel檔案(.xls/.xlsx),"[UploadPath]"這個參數要到Web.config中多新增一個上傳檔案路徑位置,檔案名稱則更改為抓取當天的日期,在儲存到相對應的路徑,最後再利用ViewBag將路徑傳送到前端顯示

[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");
}

View

  1. 前端View這邊跟前幾天有介紹到的Form表單POST傳輸一樣,所以這邊就不在多做介紹,有興趣的朋友可以看(https://ithelp.ithome.com.tw/articles/10215364) 的介紹,html的部分先新增一個input的file來選擇本地檔案(檔案送往後端Aciton的引數),新增一個span,加入ViewBag.path由後端送往前端的路徑名稱顯示
<!--點選上傳檔案按鈕後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>
  1. 接著開啟網頁點擊選擇檔案,就會出現瀏覽資料本機的彈跳視窗

  2. 選擇好Excel檔案後點擊上傳檔案後,將會出現檔案上傳成功的彈跳視窗且也會顯示檔案的上傳路徑

  3. 最後到路徑中的資料夾將會看到多新增了一筆Excel檔案上來,完成檔案上傳的功能


上一篇
[Day12]發送HTTP Request請求至Aras
下一篇
[Day14]MVC檔案下載
系列文
ArasPLM開發分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言