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 class="custom-file col-md-4">
<input type="file" class="custom-file-input" id="theFile" required="">
<label class="custom-file-label" for="theFile"></label>
</div>
<!--This is my input section-->
<div class="col-sm-3">
<div class="form-group">
<label for="fileName">Enter the file name: </label>
<input type="text" class="form-control" 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");
}
2
Answers
In
Jquery
pass the file using FormDataIn
C#
get file from request and data which is appendedYou need to add a file which name is
file
,and add a FileName which name isfileName
toformData
,so that you can get the file and filename in action:result: