javascript - 如何将文件发布到 ASP.NET Web api
问题描述
我正在尝试将图像文件从 JavaScript 单页应用程序发送到 ASP.Net Core web api,但我总是从 api 获取空异常。另外,当我在 Postman 中尝试时,Postman 工作正常,但我不想使用表单我想调用 api 并发送没有表单的文件。请帮我。这是我的代码。
JavaScript..
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);
}
}
图片上传接口..
[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;
}
}
文件始终显示为空。
解决方案
尝试
xmlHttpRequest.open('POST', target, true);
xmlHttpRequest.send(new FormData(fInput.form));
推荐阅读
- r - 使用 iframe 嵌入的 R 闪亮应用程序。如何设置链接在 iframe 之外打开?
- python-3.x - 如何使用 tkinter 创建类似终端的设计
- python - 如何在 discord.py 中安排操作?
- python - 自动获取 Mojang 不记名令牌
- ios - 接收 ITMS-90809 的电容器 iOS 应用程序:已弃用 API 使用拒绝?
- sas - sas 使用带有 substr 的 % 通配符
- javascript - 如何使用 javascript 从 mysql 获取当前月份数据?
- c# - Xamarin Forms - C# - 异步和等待不工作?
- python - Discord Bot 你如何从 dms 扮演某人?Python
- python - 在 Python 中从一列中创建多列