Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send file and text parameters using ajax on mvc

Check the jquery code below. Here, I am grabbing file from html and then post it by ajax call to my Controller Post method. And from Controller post method i am successfully receiving that file in variable called files as you can see. But my question is how can i send another two text parameters called- type and id from this ajax call then also how can i get that value from controller with that file? Basically i have to grab that file with those text value also. How is that possible? What change need in ajax and controller?

Html:

<div class="col-sm-3" style="float:left;">
                        <label class="btn btn-outline-dark btn-block">
                            Browse...
                            <span id="uploaded-file-name" style="font-style: italic"></span>
                            <input id="file-upload" type="file" name="file"
                                   onchange="$('#uploaded-file-name').text($('#file-upload')[0].value);" hidden>
                        </label>
                    </div>
                    <div class="col-sm-2" style="float:left;">
                        <button class="btn btn-dark" id="start_upload">Start Upload</button>
                    </div>

Jquery ajax:

//file upload
        $("#start_upload").click(function (evt) {
            var fileUpload = $("#file-upload").get(0);
            var files = fileUpload.files;
            var data = new FormData();
            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!");
                }
            });
        });

MVC .net core controller:

[HttpPost]
public IActionResult UploadFiles()
{
    //file upload process
    var files = Request.Form.Files;

    string type = "";
    int id = ;


}
like image 782
john Cogdle Avatar asked Sep 20 '18 02:09

john Cogdle


2 Answers

You can add the other input field values to the FormData object.

I would start by creating a viewmodel for accepting the ajax payload

public class UploadVm
{
    public string Type { set; get; }
    public string Id { set; get; }
    public HttpPostedFileBase File { set; get; }
}

Now in your view, add 2 more input elements for reading this value from user

<input id="id"   type="text" />
<input id="type" type="text" />

Now in your ajax call code, add 2 more items to the FormData object.

$("#start_upload").click(function (evt) {

    var fileUpload = $("#file-upload").get(0);
    var files = fileUpload.files;
    var data = new FormData();

    for (var i = 0; i < files.length; i++) {
        data.append("File", files[i]);
    }

    //Add the input element values
    data.append("Type", $("#type").val());
    data.append("Id", $("#id").val());

    $.ajax({
        type: "POST",
        url: "/Products/UploadFiles",
        contentType: false,
        processData: false,
        data: data,
        success: function (message) {
            console.log(message);
        },
        error: function () {
            alert("There was error uploading files!");
        }
    });

});

Now in your server side, you can use our new view model as the parameter for the action method. When the ajax call is made, the model binder will be able to map the received data from request and map it to the properties of our UploadVm view model object.

[HttpPost]
public ActionResult UploadFiles(UploadVm model)
{
    // to do : read values of model and use it
    // to do : return something
}
like image 157
Shyju Avatar answered Oct 09 '22 06:10

Shyju


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;

}
like image 29
Liakat Hossain Avatar answered Oct 09 '22 06:10

Liakat Hossain