Javascript 如何将文件发布到ASP.NET Web api
我试图将一个图像文件从JavaScript单页应用程序发送到ASP.Net核心web api,但我从api中获取了所有方式的空异常。另外,当我尝试使用Postman时,Postman工作正常,但我不想使用表单,我想调用api并发送没有表单的文件。请帮帮我。这是我的密码 JavaScriptJavascript 如何将文件发布到ASP.NET Web api,javascript,api,asp.net-web-api,xmlhttprequest,Javascript,Api,Asp.net Web Api,Xmlhttprequest,我试图将一个图像文件从JavaScript单页应用程序发送到ASP.Net核心web api,但我从api中获取了所有方式的空异常。另外,当我尝试使用Postman时,Postman工作正常,但我不想使用表单,我想调用api并发送没有表单的文件。请帮帮我。这是我的密码 JavaScript fInput = document.getElementById("fInput"); var file = fInput.files[0]; var xmlHttpRequest = n
fInput = document.getElementById("fInput");
var file = fInput.files[0];
var xmlHttpRequest = new XMLHttpRequest(),
fileName = files.name,
target = "http://localhost/ImageUploadDemo/api/ImageUpload",
mimeType = files.type;
xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpRequest.send(file);
xmlHttpRequest.onreadystatechange = function() {
debugger;
if (xmlHttpRequest.readyState == 4 && xmlHttp.status == 200) {
alert(xmlHttpRequest.responseText);
}
}
图像上传Api
[HttpPost]
public async Task<String> Index([FromForm]IList<IFormFile> files)
{
try
{
foreach (IFormFile source in files)
{
string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
if (!Directory.Exists(_environment.WebRootPath + "\\upload\\"))
{
Directory.CreateDirectory(_environment.WebRootPath + "\\upload\\");
}
using (FileStream fileStream = System.IO.File.Create(_environment.WebRootPath + "\\upload\\" + filename))
{
source.CopyTo(fileStream);
fileStream.Flush();
return "\\upload\\" + source.FileName;
}
}
return "true";
}
catch (Exception ex)
{
throw;
}
}
[HttpPost]
公共异步任务索引([FromForm]IList文件)
{
尝试
{
foreach(文件中的文件源)
{
string filename=ContentDispositionHeaderValue.Parse(source.ContentDisposition.filename.Trim(“”);
filename=this.EnsureCorrectFilename(文件名);
如果(!Directory.Exists(_environment.WebRootPath+“\\upload\\”)
{
目录.CreateDirectory(_environment.WebRootPath+“\\upload\\”);
}
使用(FileStream FileStream=System.IO.File.Create(_environment.WebRootPath+“\\upload\\”+filename))
{
CopyTo(文件流);
Flush();
返回“\\upload\\”+source.FileName;
}
}
返回“真”;
}
捕获(例外情况除外)
{
投掷;
}
}
文件始终显示为空。请尝试
xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.send(new FormData(fInput.form));
当我尝试此操作时,我得到了api中的文件,但count=0。您还有其他建议吗?您也可以发布html吗?上载图像
保存