在MVC4中上传文件而不刷新表单

时间:2015-05-21 11:17:48

标签: jquery asp.net-mvc asp.net-mvc-4

我是MVC4和Jquery的新手。
问题是我创建了一个表单,其中用户输入所有细节,并且应该上传我引用this教程的图像。但是一旦上传文件,用户输入的信息就会丢失,因为整个页面会刷新。
我不希望整个表单刷新/丢失信息。我怎么可能这样做?

以下是代码:

家庭控制器(包含2个操作方法 - FileUpload CreateLibrary ):

public class HomeController : Controller
{

FileUpload 行动方法 -

    public ActionResult FileUpload()
    {
        return View();
    }
    [HttpPost]
    public ActionResult FileUpload(HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            if (file == null)
            {
                ModelState.AddModelError("File", "Please Upload Your file");
            }
            else if (file.ContentLength > 0)
            {
                int MaxContentLength = 1024 * 1024 * 3; //3 MB
                string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf", ".docx", ".doc" };

                if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
                {
                    ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
                }

                else if (file.ContentLength > MaxContentLength)
                {
                    ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
                }
                else
                {
                    //TO:DO
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
                    file.SaveAs(path);
                    ModelState.Clear();
                    ViewBag.Message = "File uploaded successfully";
                }
            }
        }
        return View();
    }

CreateLibrary 操作方法 -

   public ActionResult CreateLibrary()
    {

        return View();
    }
    [HttpPost, ActionName("CreateLibrary")]
    [ValidateInput(false)]
    public ActionResult CreateLibRes(System.Web.Mvc.FormCollection data)//string ResultXml)//
    {
        // MessageBox.Show("Creating library");
        //  string path = Server.MapPath("~/Xsd");
        string strMyXml = Request.Form["ResultXml"].ToString();//data.Get("ResultXml");// "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Library xmlns=\"http://tempuri.org/LibraryElements.xsd\"></Library>";// Request.Form["ResultXml"].ToString();//
        //MessageBox.Show("Here:\n" + strMyXml);
        string filename = Request.Form["LibName"].ToString();
        if (filename != "")
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.LoadXml(strMyXml);
            xDoc.Save(Server.MapPath("~/Xsd/" + filename + ".library.xml"));
            MessageBox.Show("Library Saved!");
        }
        else
            MessageBox.Show("Library name not specified!");
        return View();
    }

上传文件的表格( CreateLibrary.cshtml ):

 @using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary();
        <ol>
            <li class="lifile">
                <input type="file" id="fileToUpload" name="file" />
                <span class="field-validation-error" id="spanfile"></span>
            </li>
        </ol>
        <input type="submit" id="btnSubmit" value="Upload" />
    }

在客户端验证文件: Javascript

<script type="text/jscript">
//get file size
function GetFileSize(fileid) {
    try {
        var fileSize = 0;
        //for IE
        if ($.browser.msie) {
            //before making an object of ActiveXObject,
            //please make sure ActiveX is enabled in your IE browser
            var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
            var objFile = objFSO.getFile(filePath);
            var fileSize = objFile.size; //size in kb
            fileSize = fileSize / 1048576; //size in mb
        }
            //for FF, Safari, Opeara and Others
        else {
            fileSize = $("#" + fileid)[0].files[0].size //size in kb
            fileSize = fileSize / 1048576; //size in mb
        }
        return fileSize;
    }
    catch (e) {
        alert("Error is :" + e);
    }
}

//get file path from client system
function getNameFromPath(strFilepath) {
    var objRE = new RegExp(/([^\/\\]+)$/);
    var strName = objRE.exec(strFilepath);

    if (strName == null) {
        return null;
    }
    else {
        return strName[0];
    }
}

$("#btnSubmit").live("click", function () {
    if ($('#fileToUpload').val() == "") {
        $("#spanfile").html("Please upload file");
        return false;
    }
    else {
        return checkfile();
    }
});

function checkfile() {
    var file = getNameFromPath($("#fileToUpload").val());
    if (file != null) {
        var extension = file.substr((file.lastIndexOf('.') + 1));
        // alert(extension);
        switch (extension) {
            case 'jpg':
            case 'png':
            case 'gif':
            case 'pdf':
                flag = true;
                break;
            default:
                flag = false;
        }
    }
    if (flag == false) {
        $("#spanfile").text("You can upload only jpg,png,gif,pdf extension file");
        return false;
    }
    else {
        var size = GetFileSize('fileToUpload');
        if (size > 3) {
            $("#spanfile").text("You can upload file up to 3 MB");
            return false;
        }
        else {
            $("#spanfile").text("");
        }
    }
}

$(function () {
    $("#fileToUpload").change(function () {
        checkfile();
    });
});
</script>

请指导我! 提前谢谢!

0 个答案:

没有答案