W
W
wkololo_4ever2014-05-01 11:58:45
JavaScript
wkololo_4ever, 2014-05-01 11:58:45

How to get file on ASP.NET MVC sent via XmlHttpRequest?

There is a code that sends a file to "/Home/Test"

var fileE = document.getElementById("fileAvatar");
    fileE.onchange = function ()
    {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/Home/Test");
        xhr.send(this.files[0]);
    }

How can I get this file on the server side?
Action method code
public JsonResult Test(HttpPostedFileBase fileAvatar)
        {
            return Json(new {status="OK" });
        }

does not get the file into the fileAvatar variable.
That is, how in JS to specify that this file should go to the fileAvatar variable?
UPD: I solved it by creating a FormData object. Are there other solutions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Marksimon221, 2014-05-10
@wkololo_4ever

try this
public JsonResult UploadPure()
{
string fileName = Request.Headers["X-File-Name"];
string fileType = Request.Headers["X-File-Type"];
int fileSize = int.Parse(Request.Headers["X-File-Size"]);
System.IO.Stream fileContent = Request.InputStream;
System.IO.FileStream fileStream = System.IO.File.Create(Server.MapPath("~/") + fileName);
fileContent.Seek(0, System.IO.SeekOrigin.Begin);
fileContent.CopyTo(fileStream);
fileStream.Dispose();
return Json("Uploaded files");
}
it's work for me , for more info: www.agileinfoways.com/technical-expertise/ms-techn...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question