wake-up-neo.com

Datei mit Ajax in Asp.Net Core hochladen

Guten Tag allerseits,

Ich versuche, die Datei mit ajax vom Client zum Server (asp.net core) -Controller hochzuladen.

Hier sind meine HTML- und Javascript-Codes:

<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>

Hier ist mein Controller, der IFormFile verwendet

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

Danke im Voraus!

6
jsonGPPD

Es ist gut erklärt hier :

Browserseitencode:

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

Serverseitiger Code:

[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;
}
8

Hier ist eine einfache Methode, um eine Datei zur Aktion Ihres Controllers zu posten.

Aussicht :

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) {
    }
});

Controller :

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

Sie müssen lediglich das Attribut "Name" für die Dateieingabe angeben (wie Variablenname im ASP.NET-Controller) .

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

C #:

public ActionResult UploadFile(IFormFile thefile) { }

Für die Anforderung von AJAX müssen Sie den entsprechenden Namen im FormData-Objekt angeben.

2
Alexander