【问题标题】:How to achieve File upload using WEB API Dot net core?如何使用WEB API Dot net core实现文件上传?
【发布时间】:2020-04-12 19:50:55
【问题描述】:

我正在开发 ASP DOT NET 核心 web api,我需要发送多个附件。我试过像以下

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

我收到以下错误 the server responded with a status of 400 ()

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

【问题讨论】:

  • 您不能以 JSON 格式发送并使用FormDataFormData 仅适用于 multipart/form-data 编码请求。要么发送 FormData 实例本身,要么您需要使用 FileReader 读取文件数据,然后将其作为 Base64 编码字符串以 JSON 格式发送。在后一种情况下,您必须绑定到 byte[] 而不是 IFormFile 服务器端,但序列化程序会自动处理从 Base64 字符串到 byte[] 的转换。

标签: javascript c# jquery asp.net-core asp.net-web-api


【解决方案1】:

在我需要发送多个附件的 ASP DOT NET 核心 web api 上工作

要实现它,您可以尝试修改如下代码。

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

}

测试结果

【讨论】:

  • “Model.Attachments”的类型是什么?
【解决方案2】:
<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; }
}

【讨论】:

  • 您需要将表单数据发送到服务器。然后在服务器上,您将获得文件集合。然后根据需要保存它们。
  • 感谢您的回复。我收到 415 状态代码错误。
  • 删除公共列表 附件 { get;放; } 来自模型
  • 还是同样的问题
猜你喜欢
  • 2023-03-02
  • 2020-05-27
  • 2019-10-29
  • 2011-05-10
  • 1970-01-01
  • 2019-03-10
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多