gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:21:06 24 4
gpt4 key购买 nike

我正在开发 ASP DOT NET core 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

最佳答案

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

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

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 操作

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

//code logic here

}

测试结果

enter image description here

关于javascript - 如何使用Dot net core WEB API实现文件上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59422872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com