简体   繁体   English

如何使用WEB API Dot net core实现文件上传?

[英]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.我正在研究 ASP DOT NET 核心 web api,我需要在其中发送多个附件。 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 ()我收到以下错误服务器响应状态为 400 ()

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

working on ASP DOT NET core web api where I need to send multiple attachments在 ASP DOT NET 核心 web api 上工作,我需要在其中发送多个附件

To achieve it, you can try to modify the code like below.要实现它,您可以尝试修改如下代码。

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

        }
    });
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用.NET Core 2.0 Web api上传HTML5文件 - HTML5 File upload using .NET Core 2.0 Web api 使用 ajax dot net 6 core 将文件上传到 wwwroot - upload file to wwwroot with ajax dot net 6 core ASP .NET MVC核心WEB API上传文件使用Angular JS显示错误 - ASP .NET MVC Core WEB API upload file showing error using Angular JS 如何异步上传.NET核心web API中的Word文件并保存到文件夹中 - How to upload Word file in .NET core web API asynchronously and save into a folder 使用 Angular 和 ASP WEB API CORE 上传文件? - Upload file using Angular and ASP WEB API CORE? 点网核心 Web API 与 Javascript - Z5A8FEFF0B4BDE3EEC924Z 策略错误 - Dot Net Core Web API with Javascript - CORS policy error 如何使用 React JS 以 BYTE ARRAY 格式将图像上传到 ASP.NET CORE WEB API,400 错误请求 - How to upload an image to the ASP.NET CORE WEB API in BYTE ARRAY format using React JS, 400 bad request .NET Core Web API中的IFormFile对于axios和ajax文件上载为空,但在Postman中有效 - IFormFile in .NET Core Web API is null for axios and ajax file upload but works in Postman 使用自己的Web服务api上传文件 - Upload file using own web service api 在 asp.net 核心客户端中使用 ajax 上传文件类型 - upload file type using ajax in asp.net core client
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM