【发布时间】:2015-04-18 21:09:55
【问题描述】:
我正在尝试在 ASP.NET 5 中上传文件,但我在互联网上看到的两种方式都失败了。 使用 XMLHttpRequest 这是我的服务器端代码:
public async Task<ActionResult> UploadSWF()
{
StreamReader reader = new StreamReader(Request.Body);
var text = await reader.ReadToEndAsync();
return View();
}
[EDIT 1]:我的客户端:
var client = new XMLHttpRequest();
function upload()
{
var file = document.getElementById("uploadfile");
var formData = new FormData();
formData.append("upload", file.files[0]);
client.open("post", "/Home/UploadSWF", true);
//client.setRequestHeader("Content-Type", "multipart/form-data");
client.setRequestHeader("Content-Type", "application/x-shockwave-flash");
client.send(formData);
}
但我唯一能从中得到的是:
------WebKitFormBoundaryX1h5stVbtaNe6nFw 内容处置:表单数据;名称="上传";文件名="数据.swf" 内容类型:应用程序/x-shockwave-flash CWS ;"
[EDIT 2]:这是我得到这个的代码:
public ActionResult UploadSWF()
{
Stream bodyStream = Context.Request.Body;
var sr = new StreamReader(bodyStream);
var test = sr.ReadToEnd();
return View();
}
所以我得到了文件的名称和内容类型,但没有得到它的内容。
这个答案https://stackoverflow.com/a/26445416/1203116 正在将流复制到一个文件中,但是文件创建部分对我不起作用,我不知道发生了什么但没有任何反应。所以我尝试对 MemoryStream 做同样的事情,但我得到了一个空字符串。
所以最后我尝试了另一种方法,使用 IFormFile 如下所示:https://github.com/aspnet/Mvc/blob/437eb93bdec0d9238d672711ebd7bd3097b6537d/test/WebSites/ModelBindingWebSite/Controllers/FileUploadController.cs 这个接口应该在我已经添加到我的项目中的 Microsoft.AspNet.Http 中,但我仍然无法访问它。我在这个命名空间中看不到任何 IFormFile。
[编辑 1]:我尝试的第一种方法是使用 HttpPostedFileBase,就像我在 ASP.NET MVC 5 中使用的那样,但它在我的 vNext 项目中不起作用。我总是得到一个 MissingMethodException。 我在客户端的代码是:
<form action="/home/UploadSWF" method="POST" enctype="multipart/form-data">
<input type="file" name="file" accept=".swf, application/x-shockwave-flash/*">
<input type="submit" name="submit" />
</form>
在我的控制器中:
public ActionResult UploadSWF(HttpPostedFileBase file)
{
return View();
}
【问题讨论】:
-
不确定是否有帮助,但尝试将 HttpPostedFileBase 上传参数放到 UploadSWF 中,看看它是否不为空。
-
我曾经试过这个。实际上这是我想实现的第一种方式,但我总是得到一个 MissingMethodException。请求无法到达带有经典
-
也许您也应该添加您的发布代码。
-
我花了很多时间试图弄清楚为什么我的 IFormFile 对象在我的 ASP.Net 5 OnPost() 方法中为“null”。没有错误,没有警告......也没有要上传的文件。解决方案:我忘记在
标签: c# asp.net .net asp.net-core