Reputation: 7832
I'm trying to upload a file in ASP.NET 5 but the two ways I've seen on internet fail. With XMLHttpRequest here is my server side code:
public async Task<ActionResult> UploadSWF()
{
StreamReader reader = new StreamReader(Request.Body);
var text = await reader.ReadToEndAsync();
return View();
}
[EDIT 1]: And my client side:
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);
}
But the only thing I can get from this is:
------WebKitFormBoundaryX1h5stVbtaNe6nFw Content-Disposition: form-data; name="upload"; filename="data.swf" Content-Type: application/x-shockwave-flash CWS ;"
[EDIT 2]:Here is the code how I get this:
public ActionResult UploadSWF()
{
Stream bodyStream = Context.Request.Body;
var sr = new StreamReader(bodyStream);
var test = sr.ReadToEnd();
return View();
}
So I get the name of the file and the content-type but not its content.
This answer https://stackoverflow.com/a/26445416/1203116 is copying the stream into a file however the file creation part isn't working for me, I don't know what's going on but nothing happens. So I tried to do the same with a MemoryStream and I got an empty string.
So finally I tried another way, using IFormFile like shown here: https://github.com/aspnet/Mvc/blob/437eb93bdec0d9238d672711ebd7bd3097b6537d/test/WebSites/ModelBindingWebSite/Controllers/FileUploadController.cs This interface should be in Microsoft.AspNet.Http which I've added to my project but I'm still not able to access it. I can't see any IFormFile in this namespace.
[EDIT 1]: The first method I've tried is by using HttpPostedFileBase like I was used to in ASP.NET MVC 5 but it was not working in my vNext project. I always got an MissingMethodException. My code on client side was:
<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>
And in my controller:
public ActionResult UploadSWF(HttpPostedFileBase file)
{
return View();
}
Upvotes: 7
Views: 4135
Reputation: 136
IFormFile
was introduced as part of beta3 release. You probably have outdated packages. Check your project.json
and make sure you use beta3(or newer) packages.
Upvotes: 8