Home > Net >  How to send the file name and a file from Ajax to my controller in one ajax request?
How to send the file name and a file from Ajax to my controller in one ajax request?

Time:11-18

There is an input(text) in my page so users can insert the name of the file and upload the file itself, then press on Upload button.

I want to send the selected file and its name from input(text) to my controller in one ajax request.

How does it work ?

Here is the HTML Code:

<!--This is my upload section-->
<div >
    <input type="file"  id="theFile" required="">
    <label  for="theFile"></label>
</div>

<!--This is my input section-->
<div >
    <div >
        <label for="fileName">Enter the file name: </label>
        <input type="text"  id="fileName" placeholder="">
    </div>
</div>

Here is what I tried for Ajax Code which doesn't work:

    var formData = new FormData();
    formData.append('upload', $('#questionFile')[0].files[0]);

    $.ajax({      
         url:'the url of my controller is here',
         type: 'POST',
         data: {
                'file' : formData,
                'fileName' : $("#fileName").val()
               },
         cache: false,
         processData: false,
         contentType: false
     })

Here is my method in my controller:

    [HttpPost("getFile")]
    [AllowAnonymous]
    public IActionResult getFile(IFormFile file,string fileName)
    {

        //This is a method in my service project which uploads file
        SaveQuestionFile(file, fileName);


        return Ok("Uploaded");
    }

CodePudding user response:

In Jquery pass the file using FormData

var fileData = new FormData();
var fileUpload = $("#fileId").get(0).files;
fileData.append("FILE", fileUpload[0]);
$.ajax({
    type: "POST",
    contentType: false,
    processData: false,
    url: "url here",
    data: fileData,
    success: function (result) {
    },
    error: function (data) {
    },
    complete: function () {
    }
});

In C# get file from request and data which is appended

public IActionResult getFile()
{
   List<IFormFile> files = (List<IFormFile>)Request.Form.Files;
   //if multiple
   foreach (IFormFile file in files)
   {
     string fileName = file.FileName;
   }
}

CodePudding user response:

You need to add a file which name is file,and add a FileName which name is fileName to formData,so that you can get the file and filename in action:

 var formData = new FormData();
 formData.append('file', $('#theFile').get(0).files[0]);
 formData.append('fileName', $("#fileName").val());
 $.ajax({
     type: "POST",
     url: "the url of my controller is here",
     data: formData,
     processData: false,
     contentType: false,
     success: function (data) {
     }

 });

result: enter image description here

  • Related