简体   繁体   中英

How can I send a file and a string to my backend C# from JQuery Ajax?

My UI has one input for uploading file and one input for the file's name.

I want to get both file and its name from user at the same ajax request and upload the file with the gotten name to my server.

the question is how can I get both file (binary) and the file's name from user at the same request ?

here is my try but results in 400 error.

Function in C#:

public IActionResult UploadImage(IFormFile upload, string fileWithName)
    {
      //some code here
    }

and here is my ajax:

$("#startUploading").on("click",function() {

            var fileInput = $.trim($("#myfile").val());

            var formData = new FormData();
            formData.append('upload', $('#myfile')[0].files[0]);
            formData.append('pathWithName', $("#fileAddressUploadTo").val());

            $.ajax({
                url: apiUrl+'/api/V1/Servers/UploadImage',
                type: 'POST',
                data: formData,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem('token'));
                },
                cache: false,
                processData: false,
                contentType: false
            });

           
});

400 error means bad request, but per my test I found it worked for me. So I'm afraid the issue in your code may relate to $('#myfile')[0].files[0] , see my code below

<div>
    <input type="file" id="uploadFile" />
    <button id="btn4">upload</button>
</div>

$("#btn4").click(function(){
    var form = new FormData();
    var temp = $('#uploadFile').prop('files');
    form.append("file",temp[0]);
    form.append("name","myFile");
    console.log(form);
    $.ajax({
        url: 'https://localhost:44321/hello/upload',
        type: 'POST',
        data: form,
        cache:false,
        contentType:false,//stop jquery auto convert form type to default x-www-form-urlencoded
        processData:false,
        success: function (d) {
            alert(d)
        }
    });
});


public string upload(IFormFile file, string name) { 
    return "hello";
}

在此处输入图像描述

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