简体   繁体   中英

Upload files in ASP.NET MVC C#

I have

[HttpPost]
public ActionResult GetFiles(HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
    {            
        var fileName = Path.GetFileName(file.FileName);   
        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
        file.SaveAs(path);
    }
    return Json("Uploaded " + Request.Files.Count + " files",JsonRequestBehavior.AllowGet);
}

Now I want to upload files in Ajax and save files another folder. How to get files from input form and send it via Ajax?

Try this:

cshtml:

<input id="myFile" type="file" name="myfile" onchange="GoToPreview(this)" style="display: none">



function GoToPreview(input) {
            if (input.files && input.files[0]) {  

                var tmpImageData = new FileReader();
                tmpImageData.onload = function (e) {
                    SetImageData(imageData);                
                }
                tmpImageData.readAsDataURL(input.files[0]);
            }
    }

function SetImageData(imageData) {
        $.ajax({
            url: '/Home/SetImageData',
            type: 'POST',
            data: { imageData: imageData },
            success: function (data) {
                // code here
            },
            error: function (data) {
                // code for exception
            }
        });
    }

In SetImageData method at server side do your thing.

As @Reza Aghaei already said you can use FormData to solve your problem, but i recommend you ajaxForm() method from this library . I use this approach becouse IE8 and IE9 do not support FormData

And it really is not difficult to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM