如何使用WEB API点网核心实现文件上传? [英] How to achieve File upload using WEB API Dot net core?

查看:90
本文介绍了如何使用WEB API点网核心实现文件上传?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究ASP DOT NET核心Web API,需要发送多个附件.我尝试过像

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

我遇到以下错误 服务器响应的状态为400()

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

我提到了以下问题 [1]:https://stackoverflow.com/a/49966788/9491935

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

推荐答案

在需要发送多个附件的ASP DOT NET核心Web API上工作

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客户

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) {

        }
    });
}

控制器操作

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

    //code logic here

}

测试结果

这篇关于如何使用WEB API点网核心实现文件上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆