【问题标题】:Uploading File using Ajax in Asp.Net Core在 Asp.Net Core 中使用 Ajax 上传文件
【发布时间】:2017-10-24 06:09:07
【问题描述】:

大家好,

我正在尝试使用 ajax 将文件从客户端上传到服务器端(asp.net 核心)控制器,但我的值为空。

这是我的 html 和 javascript 代码:

<input type="file" id="myfile" class="required" />
<button type="button" class="btn btn-info" onclick="uploadcsvfile()">

<script>
    function uploadcsvfile() {
       var myfile= document.getElementById("myfile");
       var formData = new FormData();

       if (myfile.files.length > 0) {
           for (var i = 0; i < myfile.files.length; i++) {
               formData.append('file-' + i, myfile.files[i]);
           }
       }

       $.ajax({
           url: "/MyController/UploadFile/",
           type: "POST",
           dataType: "json",
           data: formData,
           contentType: false,
           processData: false,
           success: function(data){

           },
           error: function (data) {

           }
        })
    }
</script>

这是我使用 IFormFile 的控制器

public async Task<JsonResult> UploadFile(IFormFile formData)
{
      // do something here
}

提前谢谢你!

【问题讨论】:

  • 现在有什么问题?你甚至会在你的操作方法上接到电话吗?
  • 服务器是否期待data: {formData:formData}formData 预计在public async Task&lt;JsonResult&gt; UploadFile(IFormFile formData) 是什么? Task&lt;JsonResult&gt; 的目的是什么?
  • @guest271314 如果我将它与大括号一起使用,我会得到 null
  • @SaurabhTiwari 我可以破坏该方法,但 formData 的值为 null
  • @jsonGPPD 你能接受一个答案吗?我刚刚尝试了 Mohammed Noureldin 的答案,这对我有用,哪一个对你有用?

标签: javascript c# jquery asp.net ajax


【解决方案1】:

很好解释here

浏览器端代码:

HTML

<form id="form" name="form" action="/uploader" enctype="multipart/form-data" method="post">
  <div class="buttons">
    <div class="upload-button">
      <div class="label">Click me!</div>
      <input id="files" name="files" type="file" size="1" multiple onchange="uploadFiles('files');" />
    </div>
  </div>
</form>

JavaScript

function uploadFiles(inputId) {
  var input = document.getElementById(inputId);
  var files = input.files;
  var formData = new FormData();

  for (var i = 0; i != files.length; i++) {
    formData.append("files", files[i]);
  }

  $.ajax(
    {
      url: "/uploader",
      data: formData,
      processData: false,
      contentType: false,
      type: "POST",
      success: function (data) {
        alert("Files Uploaded!");
      }
    }
  );
}

服务器端代码:

[HttpPost]
public async Task<IActionResult> Index(IList<IFormFile> files)
{
  foreach (IFormFile source in files)
  {
    string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Trim('"');

    filename = this.EnsureCorrectFilename(filename);

    using (FileStream output = System.IO.File.Create(this.GetPathAndFilename(filename)))
      await source.CopyToAsync(output);
  }

  return this.View();
}

private string EnsureCorrectFilename(string filename)
{
  if (filename.Contains("\\"))
    filename = filename.Substring(filename.LastIndexOf("\\") + 1);

  return filename;
}

private string GetPathAndFilename(string filename)
{
  return this.hostingEnvironment.WebRootPath + "\\uploads\\" + filename;
}

【讨论】:

  • 完美运行。
  • 在我的情况下,我发送的模型包含其他信息,例如 firstname last name 等。公共类模型 { 公共字符串名字 {get;set;} 公共列表 附件 { 获取;放;当我从 ajax 发送时,我收到 400 个状态码。如何发帖?
  • @SagarPatil 请发布一个关于该问题的新问题,并将问题的链接作为评论添加到此处,我很乐意尽我所能提供帮助。
  • @MohammedNoureldin 请在这里找到我的问题stackoverflow.com/q/59422872/9491935
  • 您在列出最佳选项方面的创造力。很漂亮
【解决方案2】:

这是一种将文件发布到控制器操作的简单方法。

查看

var formData = new FormData();
formData.append('file', $('#myfile')[0].files[0]); // myFile is the input type="file" control

var _url = '@Url.Action("UploadFile", "MyController")';

$.ajax({
    url: _url,
    type: 'POST',
    data: formData,
    processData: false,  // tell jQuery not to process the data
    contentType: false,  // tell jQuery not to set contentType
    success: function (result) {
    },
    error: function (jqXHR) {
    },
    complete: function (jqXHR, status) {
    }
});

控制器

[HttpPost]
public ActionResult UploadFile(IFormFile file)
{
    List<string> errors = new List<string>(); // added this just to return something

    if (file != null)
    {
        // do something
    }

    return Json(errors, JsonRequestBehavior.AllowGet);   
}

【讨论】:

  • 内容类型如何设置为媒体?
  • @NevilleNazerane AFAIK jquery 将自动为您的 ajax 请求设置正确的内容类型。我目前正在使用此设置在我的一个项目中上传 excel 文档。
  • 问题是,在 Asp.Net Core 中,没有 HttpPostedFileBase 而只有 IFormFile。有没有办法可以实现文件?
  • @jsonGPPD 忘记了这一点。检查更新的答案。
【解决方案3】:

您只需要指定文件输入“名称”属性(与 ASP.NET 控制器中的变量名称相同)。 HTML:

<input type="file" name="thefile" />

C#:

public ActionResult UploadFile(IFormFile thefile) { }

对于 AJAX 请求,您需要在 FormData 对象中指定适当的名称。

【讨论】:

    【解决方案4】:

    使用 (.Net Core) 的完整工作示例。从上述答案中采用的部分答案修复了编译错误。

    假设您要上传文件,那么您将提交包含已上传文件的表单。

    Register.cshtml

    @using UploadFileAjaxPostWebApp.Models.Account
    
    @model RegisterModel
    
    @using (Html.BeginForm("Register", "Account", FormMethod.Post))
    {
      <div>
        <label>First Name </label>
        <input type="text" name="FirstName" value="John" />
      </div>
      <div>
        <label>Second Name </label>
        <input type="text" name="SecondName" value="Smith" />
      </div>
      <div>
        <label>Resume</label>
        <input type="file" id="fileUpload1" onchange="uploadFiles('fileUpload1');" />
        <input type="hidden" id="ResumeFileName" name="ResumeFileName" value="@Model.ResumeFileName" />
      </div>
    
      <div>
        <input type="submit" value="Submit" />
      </div>
    }
    
    <script type="text/javascript">
    
    function uploadFiles(inputId) {
        var input = document.getElementById(inputId);
        var files = input.files;
        var formData = new FormData();
    
        for (var i = 0; i !== files.length; i++) {
            formData.append("files", files[i]);
        }
    
        $.ajax(
            {
                url: "/account/uploadfiles",
                data: formData,
                processData: false,
                contentType: false,
                type: "POST",
                success: function (data) {
                    // Set the property of the Model.
                    $("#ResumeFileName").val(data.fileName);
                    alert("Files Uploaded! " + data.fileName);
                }
            }
        );
    }
    </script>
    

    账户管理员:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using UploadFileAjaxPostWebApp.Models.Account;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Net.Http.Headers;
    
    namespace UploadFileAjaxPostWebApp.Controllers
    {
      public class AccountController : Controller
      {
        private readonly IWebHostEnvironment _hostEnvironment;
    
        public AccountController(IWebHostEnvironment hostEnvironment)
        {
            _hostEnvironment = hostEnvironment;
        }
    
        public IActionResult Register()
        {
            RegisterModel model = new RegisterModel();
    
            return View(model);
        }
    
        [HttpPost]
        public IActionResult Register(RegisterModel model)
        {
            // Handle your post action ....
            return View(model);
        }
    
        [HttpPost]
        public async Task<ActionResult> UploadFiles(IList<IFormFile> files)
        {
            string fileName = null;
    
            foreach (IFormFile source in files)
            {
                // Get original file name to get the extension from it.
                string orgFileName = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Value;
    
                // Create a new file name to avoid existing files on the server with the same names.
                fileName = DateTime.Now.ToFileTime() + Path.GetExtension(orgFileName);
    
                string fullPath = GetFullPathOfFile(fileName);
    
                // Create the directory.
                Directory.CreateDirectory(Directory.GetParent(fullPath).FullName);
    
                // Save the file to the server.
                await using FileStream output = System.IO.File.Create(fullPath);
                await source.CopyToAsync(output);
            }
    
            var response = new { FileName = fileName };
    
            return Ok(response);
        }
    
        private string GetFullPathOfFile(string fileName)
        {
            return $"{_hostEnvironment.WebRootPath}\\uploads\\{fileName}";
        }
     }
    }
    

    RegisterModel 类

    namespace UploadFileAjaxPostWebApp.Models.Account
    {
      public class RegisterModel
      {
        public string FirstName { get; set; }
    
        public string SecondName { get; set; }
    
        public string ResumeFileName { get; set; }
      }
    }
    

    【讨论】:

      【解决方案5】:

      由于参数名称不同而获取空值。

      客户端: 而不是设置文件 - 我添加 fromData same 作为您的操作方法参数名称

      formData.append('formData' myfile.files[i]);
      

      当您上传 csv 文件时,添加验证以仅允许 csv 文件。

      function uploadcsvfile() {
          var myfile= document.getElementById("myfile");
          var formData = new FormData();
          if (myfile.value.toLowerCase().lastIndexOf(".csv") == -1) 
          {
            alert("Please upload a file with .csv extension.");
            return false;
          } 
          
          // else code to upload
      }
      

      当您上传多个文件时

      Html:添加多个属性

      <input type="file" id="myfile" class="required" multiple />
      

      ServerSide:添加IFromFile列表

      public async Task<JsonResult> UploadFile(List<IFormFile> formData)
      {
            // do something here
      }
      

      如果不使用表单标签,则添加 @Html.AntiForgeryToken()

      【讨论】:

        【解决方案6】:
        var GetImages = $('[name="Images"]');
        console.log(GetImages[0].files)
        
        for (var i = 0; i != GetImages[0].files.length; i++) {
            form.append("Images", GetImages[0].files[i]);
        }
        

        【讨论】:

        • 您能否解释一下这段代码是如何解决问题的?
        • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
        猜你喜欢
        • 2021-05-31
        • 2011-06-12
        • 1970-01-01
        • 2020-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-03
        相关资源
        最近更新 更多