簡體   English   中英

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

[英]Upload files in ASP.NET MVC C#

我有

[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);
}

現在我想在 Ajax 中上傳文件並將文件保存在另一個文件夾中。 如何從輸入表單中獲取文件並通過 Ajax 發送?

嘗試這個:

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
            }
        });
    }

在服務器端的 SetImageData 方法中做你的事情。

正如@Reza Aghaei 已經說過的,您可以使用FormData來解決您的問題,但我建議您使用此庫中的ajaxForm()方法。 我使用這種方法是因為IE8 和 IE9 不支持FormData

而且真的不難使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM