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

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

问题描述

我试图用这里提到的<一个例子href="http://stackoverflow.com/questions/581703/how-to-do-a-asp-net-mvc-ajax-form-post-with-multipart-form-data/13522052#13522052">How做一个ASP.NET MVC Ajax表单后与多部分/表单数据?

不过,我不断收到失败的错误消息框

Index.cshtml

 &LT;脚本的src =〜/脚本/ jQuery的-1.8.2.min.js&GT;&LT; / SCRIPT&GT;
&LT;脚本的src =〜/脚本/ jquery.unobtrusive-ajax.min.js&GT;&LT; / SCRIPT&GT;
&LT; H2&GT;文件上传&LT; / H&GT;
&LT;脚本类型=文/ JavaScript的&GT;
$(函数(){
    $(#form0)。递交(函数(事件){
        VAR dataString;
        。事件preventDefault();
        变种行动= $(#form0)ATTR(行动)。
        如果($(#form0)。ATTR(加密类型)==的multipart / form-data的){
            //这个只适用于某些浏览器。
            //目的?到了AJAX提交文件。因为螺丝内置页框。
            //同时,我们需要调用获得(0)jQuery的元素把它变成一个普通的DOM元素,以便FORMDATA可以使用它。
            dataString =新FORMDATA($(#form0)得到(0));
            的contentType = FALSE;
            过程数据= FALSE;
        } 其他 {
            //常规的形式,做自己的事情,如果你需要它
        }
        $阿贾克斯({
            键入:POST,
            网址:动作,
            数据:dataString,
            数据类型:JSON,//改变你自己,别人看我的上述注扶持的JsonValueProviderFactory在MVC
            的contentType:contentType中,
            过程数据:过程数据,
            成功:功能(数据){
                // BTW,数据是最严重的品牌之一,你可以为一个变量

            },
            错误:函数(jqXHR,textStatus,errorThrown){
                //做自己的事
                警报(失败);
            }
        });
    }); //结束.submit()
});
&LT; / SCRIPT&GT;
&LT; D​​IV ID =uploadDiv&GT;
@ Html.Action(文件,家庭)
&LT; / DIV&GT;

@using(Ajax.BeginForm(文件,家,新AjaxOptions {UpdateTargetId =uploadDiv,HttpMethod =邮报},{新ENCTYPE =多部分/表单数据,@ ID =form0} ))
{
&LT; D​​IV&GT;
    &LT; D​​IV&GT;上传新文件:
        &LT;输入类型=文件名称=文件/&GT;&LT; / DIV&GT;
    &LT;输入类型=提交值=保存/&GT;
&LT; / DIV&GT;
}
&LT; BR /&GT;
 

控制器

 公共PartialViewResult文件(HttpPostedFileBase文件)
    {
        IEnumerable的&LT;字符串&GT;文件;
        如果((文件= NULL)及!及(file.ContentLength大于0))
        {
            字符串文件名= file.FileName;
            字符串saveLocation = @D:\文件;
            字符串fullFilePath = Path.Combine(saveLocation,文件名);


            尝试
            {
                file.SaveAs(fullFilePath);
                FileInfo的的fileInfo =新的FileInfo(fullFilePath);
                file.InputStream.Read(新字节[fileInfo.Length],0,file.ContentLength);
            }
            赶上(例外五)
            {
                TempData的[文件上传] = e.Message;
                返回PartialView();
            }
            文件= Directory.GetFiles(@D:\文件\);
            返回PartialView(文件);
        }
        其他
        {
            文件= Directory.GetFiles(@D:\文件\);
            返回PartialView(文件);
        }
    }
 

Files.cshtml

  @model IEnumerable的&LT;字符串&GT;

@foreach(字符串型F的模型)
{
&LT; P&GT; @ F&LT; / P&GT;
}
 

Global.asax中

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

解决方案

这是复杂更好地利用的jQuery插件的形式

下面是示例:

Ajax.BeginForm

  @using(Ajax.BeginForm(YourAction,YourController,新AjaxOptions(){HttpMethod =POST},{新ENCTYPE =的multipart / form-data的 }))
{
    @ Html.AntiForgeryToken()
    &LT;输入类型=文件名称=文件&GT;&LT; BR&GT;
    &LT;输入类型=提交值=上传文件到服务器&GT;
}
 

动作方法

  [HttpPost]
    [ValidateAntiForgeryToken]
    公共无效YourAction(IEnumerable的&LT; HttpPostedFileBase&GT;文件)
    {
        如果(文件!= NULL)
        {
            的foreach(在文件var文件)
            {
                //验证用户选择的文件
                如果(文件= NULL和放大器;!&安培; file.ContentLength大于0)
                {
                    //仅提取fielname
                    VAR文件名= Path.GetFileName(file.FileName);
                    // TODO:需要确定目标
                    VAR路径= Path.Combine(使用Server.Mappath(〜/上传),文件名);
                    file.SaveAs(路径);
                }
            }
        }
    }
 

进度条

 &LT; D​​IV CLASS =进步进步条纹&GT;
        &LT; D​​IV CLASS =进度条进度条 - 成功大于0%&LT; / DIV&GT;
    &LT; / DIV&GT;

&LT; D​​IV ID =状态&GT;&LT; / DIV&GT;
 

jQuery和放大器;表脚本

 &LT;脚本SRC =htt​​p://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js&GT;&LT; / SCRIPT&GT;
&所述;脚本的src =htt​​p://malsup.github.com/jquery.form.js&GT;&所述; /脚本&GT;

&LT;脚本&GT;
(功能() {

VAR栏= $('。进度条);
VAR百分比= $('。进度条);
VAR状态= $('#状态');

$('表')。当作ajaxForm({
    beforeSend:函数(){
        status.empty();
        变种percentVal =0%;
        bar.width(percentVal)
        percent.html(percentVal);
    },
    上传进度:功能(事件,位置,共有percentComplete){
        VAR percentVal = percentComplete +'%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    成功:函数(){
        VAR percentVal =100%;
        bar.width(percentVal)
        percent.html(percentVal);
    },
    完成:功能(XHR){
        status.html(xhr.responseText);
    }
});

})();
&LT; / SCRIPT&GT;
 

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:

Ajax.BeginForm

 @using (Ajax.BeginForm("YourAction", "YourController", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"}))
{
    @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>

<div id="status"></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>

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆