iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 25
1
自我挑戰組

後端或是ASP.NET Core的學習筆記系列 第 25

第25天:實作檔案上傳功能(2)

昨天講到在Controller的AddProduct Action要接受繫結的參數改成AddProductViewModel。

[HttpPost]
public IActionResult AddProduct(AddProductViewModel productViewModel)
{
 ...
}

接下來我們拿到的productViewModel裡面有包含使用者上傳的檔案IFormFile後,要將檔案轉存到指定資料夾,並指定一個新的檔案名稱(為了避免檔案名稱重複),這邊我指定data資料夾,依你的執行環境而定,目前我的測試專案會從C槽起始找data資料夾並寫入。

[HttpPost]
public IActionResult AddProduct(AddProductViewModel productViewModel)
{
 ...
    //取得使用者上傳檔案的原始檔名
    var fileOriginName = Path.GetFileName(productViewModel.File.FileName);
    //取原始檔名中的副檔名
    var fileExt = Path.GetExtension(fileOriginName);
    //為避免使用者上傳的檔案名稱發生重複,重新給一個亂數名稱
    var fileNewName = Path.GetRandomFileName();
    //指定要寫入的路徑、檔名和副檔名
    var filePath = "/data/" + fileNewName + fileExt;

    //將使用者上傳的檔案寫入到指定路徑
    using (var stream = System.IO.File.Create(filePath))
    {
        //執行寫入
        productViewModel.File.CopyToAsync(stream);
    }
    ...
}

在你按下送出按鈕後,執行完CopyToAsync就會看到檔案被寫進你指定的目錄中,並且是一個隨機名稱
https://ithelp.ithome.com.tw/upload/images/20201010/20120420nZyzHMn44J.png
https://ithelp.ithome.com.tw/upload/images/20201010/201204209X8zxt8s85.png

那目前的程式還不能上傳太大的檔案,以及目前資料庫要並不會紀錄檔案的圖片路徑
這些問題就明天再說吧@@


上一篇
第24天:實作檔案上傳功能(1)
下一篇
第26天:實作檔案上傳功能(3)
系列文
後端或是ASP.NET Core的學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言