简体   繁体   English

在 ASP.NET MVC C# 中上传文件

[英]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.现在我想在 Ajax 中上传文件并将文件保存在另一个文件夹中。 How to get files from input form and send it via Ajax?如何从输入表单中获取文件并通过 Ajax 发送?

Try this:尝试这个:

cshtml: 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.在服务器端的 SetImageData 方法中做你的事情。

As @Reza Aghaei already said you can use FormData to solve your problem, but i recommend you ajaxForm() method from this library .正如@Reza Aghaei 已经说过的,您可以使用FormData来解决您的问题,但我建议您使用此库中的ajaxForm()方法。 I use this approach becouse IE8 and IE9 do not support FormData我使用这种方法是因为IE8 和 IE9 不支持FormData

And it really is not difficult to use it.而且真的不难使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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