简体   繁体   中英

How to achieve File upload using WEB API Dot net core?

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

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

在此处输入图片说明

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

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