1

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

           
});
3
  • "mimeType": "multipart/form-data" ? Commented Jun 6, 2022 at 6:55
  • set name of your inputs as c# names and in your ajax use : data = new FormData($frm[0]) Commented Jun 6, 2022 at 7:46
  • your js set formData.append('pathWithName', and your api set input parameter string fileWithName, but it also won't lead to 400 Commented Jun 6, 2022 at 8:29

1 Answer 1

4

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";
}

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.