1. 程式人生 > 實用技巧 >君仙的.net core 上傳檔案

君仙的.net core 上傳檔案

 1  [HttpPost]    //上傳檔案是 post 方式,這裡加不加都可以
 2         public async Task<IActionResult> UploadFiles(List<IFormFile> files)
 3         {
 4            
 5             var filepath = Directory.GetCurrentDirectory() + "\\file";  //儲存檔案的路徑
 6 
 7 
 8             foreach (var item in files)     //上傳選定的檔案列表
9 { 10 if (item.Length > 0) //檔案大小 0 才上傳 11 { 12 var thispath = filepath + "\\" + item.FileName; //當前上傳檔案應存放的位置 13 14 if (System.IO.File.Exists(thispath) == true) //如果檔案已經存在,跳過此檔案的上傳 15 {
16 continue; 17 } 18 19 //上傳檔案 20 using (var stream = new FileStream(thispath, FileMode.Create)) //建立特定名稱的檔案流 21 { 22 try 23 { 24 await
item.CopyToAsync(stream); //上傳檔案 25 } 26 catch (Exception) 27 { 28 } 29 30 } 31 } 32 } 33 return View(); 34 }
View Code

上面的是控制器,下面的是頁面

 1 @{
 2     ViewData["Title"] = "Upload";
 3 }
 4 
 5 <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="UploadFiles">
 6     <div class="form-group">
 7         <div class="col-md-12">
 8             <p>選擇要上傳的檔案</p>
 9             <input type="file" name="files" multiple />
10         </div>
11     </div>
12     <div class="form-group">
13         <div class="col-md-12">
14             <input type="submit" value="上傳" />
15         </div>
16     </div>
17 </form>
View Code

就這些