Dynamic Table Name in Linq

How to upload files using ajax to asp.net mvc controller action

Unfortunately the jQuery serialize() method will not include input file elements. So your files are not going to be included in the serialized value.

What you can do is, creating a FormData object, append the files to that. You need to append the form field values as well to this same FormData object. You may simply loop through all the input field and add it.

When you add the files to form data, you need to give a name which will match with the parameter you will use in your HttpPost action method.

This should work.

var fileUpload = $("#productImg").get(0);
var files = fileUpload.files;

var formData = new FormData();

// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
console.log('(files[i].name:' + files[i].name);
formData.append('productImg', files[i]);
}

// You can update the jquery selector to use a css class if you want
$("input[type='text'").each(function (x, y) {
formData.append($(y).attr("name"), $(y).val());
});

$.ajax({
type: 'POST',
url: 'ReplaceHereYourUrltotheActionMethod',
data: formData,
processData: false,
contentType: false,
success: function (data) {
}
});

and your action method, You can add another parameter of type IEnumerable<HttpPostedFileBase> with the name same as what we set to form data, which is productImg.

[HttpPost]
public virtual ActionResult Index(ProductModel model,
IEnumerable<HttpPostedFileBase> productImg)
{
// to do :Look through productImg and do something
}

jQuery ajax upload file in asp.net mvc

Upload files using AJAX in ASP.Net MVC

Things have changed since HTML5

JavaScript

document.getElementById('uploader').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
return false;
}

Controller

public JsonResult Upload()
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i]; //Uploaded file
//Use the following properties to get file's name, size and MIMEType
int fileSize = file.ContentLength;
string fileName = file.FileName;
string mimeType = file.ContentType;
System.IO.Stream fileContent = file.InputStream;
//To save file, use SaveAs method
file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
}
return Json("Uploaded " + Request.Files.Count + " files");
}

EDIT : The HTML

<form id="uploader">
<input id="fileInput" type="file" multiple>
<input type="submit" value="Upload file" />
</form>

send file and text parameters using ajax on mvc

What i am doing here is, just insert key with values into this FormData() obj from jquery then you can grab it from your controller. If you want to know more about FormData() then read here

Change your jquery to this-

//file upload
$("#start_upload").click(function (evt) {
var fileUpload = $("#file-upload").get(0);
var files = fileUpload.files;
var data = new FormData();
data.append('type', 'your_type');
data.append('id', '1');

for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
type: "POST",
url: "/Products/UploadFiles",
contentType: false,
processData: false,
data: data,
success: function (message) {
alert(message);
},
error: function () {
alert("There was error uploading files!");
}
});
});

Then grab those value by its key from controller:

[HttpPost]
public IActionResult UploadFiles()
{
//file upload process
var files = Request.Form.Files;
string type = Request.Form.Where(x => x.Key == "type").FirstOrDefault().Value;
string id = Request.Form.Where(x => x.Key == "id").FirstOrDefault().Value;

}

File Upload Through JQuery AJAX In ASP.NET MVC

Change the function SendInvite() as:

function SendInvite() {
//Check validations for other inputs on the page

//Get the excel file same as above
var excelFile = document.getElementById('ExcelFile');
formData = new FormData();

formData.append("data", JSON.stringify(myModel));

for (var i = 0; i < excelFile.files.length; i++) {
var file = ExcelFile.files[i];
formData.append("excelFile", file);
}
$.ajax({
type: "POST",
url: url here,
data: formData,
contentType: "application/json; charset=utf-8",
dataType: "json",
contentType: false,
processData: false,
success: function (data) {
},
error: function (data) {
}
});
}

and in controller

public JsonResult MyController2(string data, HttpPostedFileBase[] excelFile)
{
MyModel myModel = JsonConvert.DeserializeObject<MyModel>(data);
if (Request.Files.Count > 0)
{
//Do data processing here
}

//Further processing

Check this link How to Pass Image File and Form Data From Ajax to MVC Controller

Uploading image file with ajax and receiving it with in the asp.net core mvc controller

The ajax post request gets received by the controller's action,
however the IFormFile image is always null.

When the file is uploaded by formData append, the name at this time should be the same as "image" of the receiving parameter in action:

formData.append("image", files[0]);

And because you only need to pass the IFormFile to the action, in the data parameter of ajax, you only need to put the formData which appends the file named Image to it:

 data: formData,

Change your js as follow:

function photoUploadConfirmed() {
event.preventDefault();
var files = $("#image")[0].files;
var formData = new FormData();
formData.append("image", files[0]);
console.log(files); // I just check here and in browser I can see file name and size
console.log(formData); // I expect to see the same here, but here it almost shows empty
$.ajax({
type: "POST",
url: "/Account/ChangeProfilePicture",
data: formData, // In the controller it receives IFormFile image
processData: false,
contentType: false,
success: function () {
console.log("Done");
$("#profilePhoto").val('');
$("#profPicUploadConfirm").attr("disabled", true);
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
}

Here is the test result:

enter image description here

Uploading file AND text to server using Ajax in asp.net mvc

  1. Changed the Upload method to take in a string parameter named fileText.

Correct.


  1. Changed the script to also appent the text to the formdata with these two lines inside the for-loop:

Incorrect. You shouldn't be doing this inside the loop because you have only one input field for the text, so you can send only 1 value. So move this code outside of the loop. Also you should specify the correct name when appending to the FormData which must match your controller action parameter name:

var fileText = document.getElementById('fileText');
formdata.append('fileText', fileText.value);


Related Topics



Leave a reply



Submit