asp.net core mvc實作檔案上傳實例

高洛峰
發布: 2017-02-07 11:33:03
原創
1166 人瀏覽過

工作用到檔案上傳的功能,在這個分享下~~

Controller:        

public class PictureController : Controller
  {
    private IHostingEnvironment hostingEnv;
 
    public PictureController(IHostingEnvironment env)
    {
      this.hostingEnv = env;
    }
    // GET: /<controller>/
    public IActionResult Index()
    {
      return View();
    }
    public IActionResult UploadFiles()
    {
      return View();
    }
    [HttpPost]
    public IActionResult UploadFiles(IList<IFormFile> files)
    {
      long size = 0;
      foreach (var file in files)
      {
        var filename = ContentDispositionHeaderValue
                .Parse(file.ContentDisposition)
                .FileName
                .Trim(&#39;"&#39;);
        //这个hostingEnv.WebRootPath就是要存的地址可以改下
        filename = hostingEnv.WebRootPath + $@"\{filename}";
        size += file.Length;
        using (FileStream fs = System.IO.File.Create(filename))
        {
          file.CopyTo(fs);
          fs.Flush();
        }
      }
      ViewBag.Message = $"{files.Count} file(s) /{ size}bytes uploaded successfully!";
       return View();
    }
 
  }
登入後複製

view:

<form asp-action="UploadFiles"
         asp-controller="Picture"
         method="post"
         enctype="multipart/form-data">
        <input type="file" name="files" multiple />
        <input type="submit" value="Upload Selected Files" />
 </form>
登入後複製

檔案是上傳到wwwroot目錄檔案下的,這也不太懂交流~~

--------------------------------------------- -------------------------------------------------- -----------

下面是jquery ajax方式上傳的

post方式的action的z參數沒用因為只有一個post方式的會404錯誤所以又加了一個get的action

Controller: 

public IActionResult UploadFilesAjax()
{
  return View();
}
[HttpPost]
public IActionResult UploadFilesAjax(string z) 
{
  long size = 0;
  var files = Request.Form.Files;
  foreach (var file in files)
  {
    var filename = ContentDispositionHeaderValue
            .Parse(file.ContentDisposition)
            .FileName
            .Trim(&#39;"&#39;);
    filename = @"C:\Users\lg.HL\Desktop" + $@"\{filename}";    
    size += file.Length;
    using (FileStream fs = System.IO.File.Create(filename))
    {
      file.CopyTo(fs);
      fs.Flush();
    }
  }
  string message = $"{files.Count} file(s) / { size}bytes uploaded successfully!";
    return Json(message);
}
登入後複製

view

<form method="post" enctype="multipart/form-data">
      <input type="file" id="files"
          name="files" multiple />
      <input type="button"
          id="upload"
          value="Upload Selected Files" />
 </form>
登入後複製

jquery

<script type="text/javascript">
    $(document).ready(function () {
      $("#upload").click(function (evt) {
        var fileUpload = $("#files").get(0);
        var files = fileUpload.files;
        var data = new FormData();
        for (var i = 0; i < files.length ; i++) {
          data.append(files[i].name, files[i]);
        }
        $.ajax({
          type: "POST",
          url: "/Picture/UploadFilesAjax",
          contentType: false,
          processData: false,
          data: data,
          success: function (message) {
            alert(message);
          },
          error: function () {
            alert("There was error uploading files!");
          }
        });
      });
    });
</script>
登入後複製

   


歡迎大家

更多asp.net core mvc實作檔案上傳實例相關文章請關注PHP中文網!


相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板