1

I am working on ASP DOT NET core web api where I need to send multiple attachments. I tried like following

<input type="text" id="txt_firstName"  />
<input type="text" id="txt_lastName"  />
<input type="file" id="file_TicketManageMent_AttachFile" multiple  />
<input type="button" onclick="fnADD()"  />

<script>
function fnADD(){
  var input = document.getElementById('file_TicketManageMent_AttachFile');
  var files = fileList;
  var formData = new FormData();

  for (var i = 0; i != files.length; i++) {
    formData.append("files", files[i]);
  }

  var mdl = {};
    mdl.FirstName = 'Title';
    mdl.LastName = 'Short Description';
    mdl.Attachments = formData;

  $.ajax({
    cache: false,
    type: 'Post',           
    contentType: 'application/json',
    data: JSON.stringify(mdl),
    url: fnApiRequestUri('api/Customer/AddTicket'),
    success: function (xhr, ajaxOptions, thrownError) {
    }
  });
}
</script>

//C# code
[Route("AddTicket")]
[HttpPost]
[Authorize(Roles = MethodsAuthorization.AllRoles)]
public async Task<IActionResult> AddTicket(Model _model)
{
}

public class Model
{
  public string FirstName {get;set;}
  public string LastName {get;set;}
  public List<IFormFile> Attachments { get; set; }
}

I am getting following error the server responded with a status of 400 ()

I referred following question [1]: https://stackoverflow.com/a/49966788/9491935

1
  • 2
    You can't send as JSON and use FormData. FormData is only applicable for multipart/form-data encoded requests. Either send the FormData instance itself, or you need to read the file data using FileReader and then send it in the JSON as a Base64-encoded string. In the latter case, you'll have to bind to byte[] rather than IFormFile server-side, but the serializer will automatically take care of converting from Base64 string to byte[]. Commented Dec 20, 2019 at 15:42

2 Answers 2

3

working on ASP DOT NET core web api where I need to send multiple attachments

To achieve it, you can try to modify the code like below.

Js client

function fnADD() {
    var input = document.getElementById('file_TicketManageMent_AttachFile');
    var files = input.files;
    var formData = new FormData();

    for (var i = 0; i != files.length; i++) {
        formData.append("Attachments", files[i]);
    }

    formData.append("FirstName", 'Title');
    formData.append("LastName", 'Short Description');

    $.ajax({
        cache: false,
        type: 'Post',
        data: formData,
        url: '{your_url_here}',
        processData: false,
        contentType: false,
        success: function (xhr, ajaxOptions, thrownError) {

        }
    });
}

Controller action

[Route("AddTicket")]
[HttpPost]
[Authorize(Roles = MethodsAuthorization.AllRoles)]
public async Task<IActionResult> AddTicket([FromForm]Model _model)
{

    //code logic here

}

Test Result

enter image description here

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

2 Comments

What is the type of "Model.Attachments"?
@DaveتMaher IFormFile
0
<input type="text" id="txt_firstName"  />
<input type="text" id="txt_lastName"  />
<input type="file" id="file_TicketManageMent_AttachFile" multiple  />
<input type="button" onclick="fnADD()"  />

<script>
function fnADD(){
       var input = document.getElementById('file_TicketManageMent_AttachFile');
       var files = fileList;
       var formData = new FormData();

       for (var i = 0; i != files.length; i++) {
          formData.append("files", files[i]);
       }

        formData.append("FirstName ", 'Title');
        formData.append("LastName ", 'Short Description');

     $.ajax({
            cache: false,
            type: 'Post',           
            data: formData,
            url: fnApiRequestUri('api/Customer/AddTicket'),
            processData: false,
            contentType: false,
            success: function (xhr, ajaxOptions, thrownError) {

            }
        });
}
</script>

//C# code
[Route("AddTicket")]
[HttpPost]
[Authorize(Roles = MethodsAuthorization.AllRoles)]
public async Task<IActionResult> AddTicket(Model _model)
{
     var files = Request.Form.Files;
     foreach(var item in files)
     {
        var file = item;
        if (file != null)
        {
            var fileName = file.FileName;
            if (System.IO.File.Exists(path + fileName))
            {
                fileName = $"{DateTime.Now.ToString("ddMMyyyyHHmmssfff")}-{fileName}";
            }
            using (var fileStream = new FileStream(path + fileName, FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
            reg.Picture = fileName;
        }
     }

}

public class Model
{
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public List<IFormFile> Attachments { get; set; }
}

4 Comments

You need to send form data to server. And then on the server you will get collection of files. And then save them as you want.
Thank you for your response. I am getting 415 status code error.
Remove public List<IFormFile> Attachments { get; set; } from model
Still same problem

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.