简体   繁体   中英

Sending photos and multiple data to the controller with ajax

I am sending the selected photo to my controller in asp.net core with ajax and javascript. Thanks to the code below:

<form id="form" name="form" style="display:none;" method="post" enctype="multipart/form-data">
    <div class="row">
        <div class="col-md-12">
            <input  onchange="uploadFiles('files');" class="form-control" type="file" id="files">
        </div>
    </div>
</form>

My javascript and ajax codes:

var sliderFotografEkle = "@Url.Action("sliderFotoKayit", "slider")";

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: sliderFotografEkle,
            data: formData,
            processData: false,
            contentType: false,
            type: "POST",
            success: function (data) {
                alert("Files Uploaded!");
            }
        }
    );
}

It only takes formData in the data part. I want to send a second data. It doesn't send. Probably processData: false, contentType: false, from what I gave. but if i don't give them it doesn't send the photo this time. Please help me.

this is where the parameters are given in the controller:

[HttpPost]
public async Task<IActionResult> sliderFotoKayit(slider item, List<IFormFile> files)

I already tested your code on ASP.NET Core 3.1 and found no problem uploading one file at a time.

As I understand, you problem is that you cannot choose and send multiple files at once.

For choosing and sending multiple files at once, your html input tag must have a multiple attribute. Otherwise, it only allows you to choose one file at a time.

<input onchange="uploadFiles('files');" class="form-control" type="file" id="files" multiple>

Updated after the author provided more context:

For any additional value you want to send in your form data, just you append(key: string, value: any) method.

Updated JS with an additional int field:

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

    formData.append("id", 3); // append additional int field here

    $.ajax(
        {
            url: sliderFotografEkle,
            data: formData,
            processData: false,
            contentType: false,
            type: "POST",
            success: function (data) {
                alert("Files Uploaded!");
            }
        }
    );
}
</script>

Controller method signature to receive files and an additional int field:

[HttpPost]
public async Task<IActionResult> HandleFileUpload(int id, List<IFormFile> files)

Some more details:

When you send form data to the server, request will have content-type: multipart/form-data; . As one HTTP request can just have one content-type, there are 2 choices:

  • The easy way: Add new fields to form, either through input fields in html or formData.append(key, value) in js. This is recommended because:

    1. content-type: multipart/form-data; can include both files and any other types that HTML form support.
    2. content-type: multipart/form-data; has built-in support in ASP.NET, so form content will automatically bind to controller method parameters.
  • The hard way: Serialize formdata into string, then return content-type: application/json; . Do this if you don't have control over the server, usually in cases when you have to conform to the API of another server. This is clearly more flexible, but also more complicated.

You will be able to have the data in the form:

{
    "formData": serializedFormData, 
    "id": id
}

The biggest drawback is that the server then have to manually deserialize the form data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM