MVC中的Ajax.BeginForm上传文件 [英] Ajax.BeginForm in MVC to upload files

查看:30
本文介绍了MVC中的Ajax.BeginForm上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用这里提到的一个例子 如何使用 multipart/form-data 进行 ASP.NET MVC Ajax 表单发布?

但我不断收到失败"错误消息框

索引.cshtml

<script src="~/Scripts/jquery-1.8.2.min.js"></script><script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script><h2>文件上传</h2><script type="text/javascript">$(函数(){$("#form0").submit(function(event) {变量数据字符串;event.preventDefault();var action = $("#form0").attr("action");if ($("#form0").attr("enctype") == "multipart/form-data") {//这只适用于某些浏览器.//目的?通过ajax提交文件.因为螺丝 iframe.//此外,我们需要在 jQuery 元素上调用 .get(0) 将其转换为常规 DOM 元素,以便 FormData 可以使用它.dataString = new FormData($("#form0").get(0));内容类型 = 假;进程数据 = 假;} 别的 {//常规形式,如果需要就做你自己的事}$.ajax({类型:POST",网址:行动,数据:数据字符串,dataType: "json",//改为你自己的,否则请阅读我上面关于在 MVC 中启用 JsonValueProviderFactory 的说明内容类型:内容类型,流程数据:流程数据,成功:功能(数据){//顺便说一句,数据是您可以为变量命名的最糟糕的名称之一},错误:函数(jqXHR,textStatus,errorThrown){//做你自己的事警报(失败");}});});//结束 .submit()});<div id="uploadDiv">@Html.Action("文件", "主页")

@using (Ajax.BeginForm("Files", "Home", new AjaxOptions { UpdateTargetId = "uploadDiv", HttpMethod = "Post" }, new { enctype = "multipart/form-data", @id="form0"})){<div><div>上传新文件:<input type="file" name="file"/></div><input type="submit" value="保存"/>

}<br/>

控制器

public PartialViewResult 文件(HttpPostedFileBase 文件){IEnumerable档案;if ((file != null) && (file.ContentLength > 0)){字符串文件名 = 文件.文件名;string saveLocation = @"D:Files";string fullFilePath = Path.Combine(saveLocation, fileName);尝试{file.SaveAs(fullFilePath);FileInfo fileInfo = new FileInfo(fullFilePath);file.InputStream.Read(new byte[fileInfo.Length], 0, file.ContentLength);}捕获(例外 e){TempData["FileUpload"] = e.Message;返回 PartialView();}files = Directory.GetFiles(@"D:Files");返回 PartialView(文件);}别的{files = Directory.GetFiles(@"D:Files");返回 PartialView(文件);}}

文件.cshtml

@model IEnumerable@foreach(模型中的字符串 f){<p>@f</p>}

Global.asax

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

解决方案

那就复杂了最好使用 jquery forms plugin.

这是示例:

Html.BeginForm

 @using (Html.BeginForm("YourAction", "YourController")){@Html.AntiForgeryToken()<input type="file" name="files"><br><input type="submit" value="上传文件到服务器">}

动作方法

 [HttpPost][验证AntiForgeryToken]public void YourAction(IEnumerable files){如果(文件!= null){foreach(文件中的var文件){//验证用户是否选择了一个文件if (file != null && file.ContentLength > 0){//只提取文件名var fileName = Path.GetFileName(file.FileName);//TODO: 需要定义目的地var path = Path.Combine(Server.MapPath("~/Upload"), fileName);文件.另存为(路径);}}}}

进度条

<div class="progress-bar progress-bar-success">0%</div>

Jquery &表单脚本

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script><script src="http://malsup.github.com/jquery.form.js"></script><脚本>(功能() {var bar = $('.progress-bar');var 百分比 = $('.progress-bar');var status = $('#status');$('form').ajaxForm({发送前:函数(){状态.空();var percentVal = '0%';bar.width(percentVal)百分比.html(percentVal);},上传进度:功能(事件,位置,总计,百分比完成){var percentVal = percentComplete + '%';bar.width(percentVal)百分比.html(percentVal);},成功:函数(){var percentVal = '100%';bar.width(percentVal)百分比.html(percentVal);},完成:功能(xhr){status.html(xhr.responseText);}});})();

更新...

出现两次调用 action 方法问题的人是由于 Ajax.BeginForm,只需将其转换为 Html.BeginForm().有关更多说明和下载示例代码,请参阅这个博客.

I was trying to use an example mentioned here How to do a ASP.NET MVC Ajax form post with multipart/form-data?

But I keep getting "fail" error message box

Index.cshtml

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<h2>Files Upload</h2>
<script type="text/javascript">
$(function() {
    $("#form0").submit(function(event) {
        var dataString;
        event.preventDefault();
        var action = $("#form0").attr("action");
        if ($("#form0").attr("enctype") == "multipart/form-data") {
            //this only works in some browsers.
            //purpose? to submit files over ajax. because screw iframes.
            //also, we need to call .get(0) on the jQuery element to turn it into a regular DOM element so that FormData can use it.
            dataString = new FormData($("#form0").get(0));
            contentType = false;
            processData = false;
        } else {
            // regular form, do your own thing if you need it
        }
        $.ajax({
            type: "POST",
            url: action,
            data: dataString,
            dataType: "json", //change to your own, else read my note above on enabling the JsonValueProviderFactory in MVC
            contentType: contentType,
            processData: processData,
            success: function(data) {
                //BTW, data is one of the worst names you can make for a variable

            },
            error: function(jqXHR, textStatus, errorThrown) {
                //do your own thing
                alert("fail");
            }
        });
    }); //end .submit()
});
</script>
<div id="uploadDiv">
@Html.Action("Files", "Home")
</div>

@using (Ajax.BeginForm("Files", "Home", new AjaxOptions { UpdateTargetId = "uploadDiv", HttpMethod = "Post" }, new { enctype = "multipart/form-data", @id="form0"}))
{
<div>
    <div>Upload new file:
        <input type="file" name="file" /></div>
    <input type="submit" value="Save" />
</div>
}
<br />

Controller

public PartialViewResult Files(HttpPostedFileBase file)
    {
        IEnumerable<string> files;
        if ((file != null) && (file.ContentLength > 0))
        {
            string fileName = file.FileName;
            string saveLocation = @"D:Files";
            string fullFilePath = Path.Combine(saveLocation, fileName);               


            try
            {
                file.SaveAs(fullFilePath);
                FileInfo fileInfo = new FileInfo(fullFilePath);
                file.InputStream.Read(new byte[fileInfo.Length], 0, file.ContentLength);                    
            }
            catch (Exception e)
            {
                TempData["FileUpload"] = e.Message;
                return PartialView();
            }
            files = Directory.GetFiles(@"D:Files");
            return PartialView(files);
        }
        else
        {
            files = Directory.GetFiles(@"D:Files");
            return PartialView(files);
        }
    }

Files.cshtml

@model IEnumerable<string>

@foreach (string f in Model)
{
<p>@f</p>
}

Global.asax

ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());

解决方案

That is complicated better use jquery forms plugin.

Here is the sample:

Html.BeginForm

 @using (Html.BeginForm("YourAction", "YourController"))
{
    @Html.AntiForgeryToken()
    <input type="file" name="files"><br>
    <input type="submit" value="Upload File to Server">
}

Action Method

    [HttpPost]
    [ValidateAntiForgeryToken]
    public void YourAction(IEnumerable<HttpPostedFileBase> files)
    {
        if (files != null)
        {
            foreach (var file in files)
            {
                // Verify that the user selected a file
                if (file != null && file.ContentLength > 0)
                {
                    // extract only the fielname
                    var fileName = Path.GetFileName(file.FileName);
                    // TODO: need to define destination
                    var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
                    file.SaveAs(path);
                }
            }
        }
    }

Progress Bar

<div class="progress progress-striped">
   <div class="progress-bar progress-bar-success">0%</div>
</div>

Jquery & Form script

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>

<script>
(function() {

var bar = $('.progress-bar');
var percent = $('.progress-bar');
var status = $('#status');

$('form').ajaxForm({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    success: function() {
        var percentVal = '100%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    complete: function(xhr) {
        status.html(xhr.responseText);
    }
}); 

})();       
</script>

Update...

People who are getting issue of calling action method twice is due to Ajax.BeginForm, just convert it to Html.BeginForm(). For more clarification and to download sample code please refer at this blog.

这篇关于MVC中的Ajax.BeginForm上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆