我如何prevent IE在asp.net mvc的文件上传使用时保存文件对话框 [英] How do I prevent IE save file dialog when using fileupload in asp.net mvc

查看:135
本文介绍了我如何prevent IE在asp.net mvc的文件上传使用时保存文件对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试和上传使用ASP.NET MVC的文件,它工作正常在FF&放大器;&安培;铬,但在IE和Opera一个对话框弹出,它要求我要么下载,保存或取消。

选择任一选项,$ P $从工作pvents的文件上传。我怎样才能克服这个问题?

 公共类ImportModel
    {
        [需要]
        [FileExtensions(CSV的ErrorMessage =请上传有效的.csv文件)]
        公共HttpPostedFileBase文件{搞定;组; }
    }[HttpPost]
    公共虚拟的ActionResult StartImport(ImportModel模型= NULL)
    {
        如果(型号!= NULL)
        {
            VAR状态= _importService.StartImport(模型);
            返回JSON(状态,JsonRequestBehavior.AllowGet);
        }
        返回null;
    }

查看code以下(总结):

 < D​​IV ID =dlgImport级=隐藏>        @using(Html.BeginForm(MVC.Import.StartImport(),FormMethod.Post,新{@class =smallFormID =frmImport,ENCTYPE =的multipart / form-data的}))
        {
            < D​​IV CLASS =字段内联>
                < D​​IV CLASS =编辑标记>
                    @ Html.Label(文件)
                < / DIV>
                < D​​IV CLASS =主编场>
                    @ Html.TextBoxFor(X => x.File,新{@类=输入文件,类型=​​文件})
                    @ Html.ValidationMessageFor(X => x.File)
                < / DIV>
            < / DIV>
        }
    < / DIV>< / DIV>$(函数(){
        $(#frmImport)。当作ajaxForm({
            成功:函数(responseHtml){
                //响应由浏览器包裹在pre标签 - 阿贾克斯上传使用iframe进行
                变种响应= $ .parseJSON($(responseHtml)的.text());
            }
        });
});
 VAR VM = {        startImport:功能(){            如果($(#frmImport)。有效()){
                $(#frmImport)提交()。
            }
        }    }


解决方案

现在,您已经发布您的code,它看起来像你正在使用的的jQuery插件的形式。由于文档这个插件在解释支持使用AJAX文件上传,但你不能从你的服务器端脚本返回JSON:


  

既然是不可能使用上传文件浏览器的
  XMLHtt prequest对象,这个插件使用一个隐藏的iframe元素
  与任务帮助。这是一种常用的技术,但它具有固有的
  限制。 iframe元素作为表单的目标
  提交操作,这意味着在服务器响应写入
  iframe中。这是好的,如果响应类型是HTML或XML,但
  如果数据类型是script或JSON不工作为好,两者的
  这往往包含需要利用实体repesented字符
  当一些HTML代码引用。


  
  

要占脚本和JSON响应的挑战,表
  插件允许嵌入到textarea元素,这些反应和
  建议您为这些响应类型这样做在使用时
  与一起选择文件上传。请注意,但是,如果有
  在表单中没有文件输入则请求使用正常XHR提交
  形式(而不是一个iframe)。这使负担您的服务器code到
  知道什么时候使用一个textarea,何时不。


所以基本上你上传的控制器操作应响应:

 < TextArea> {foo的栏}< / textarea的>

而不是:

  {foo的栏}

此外,你不应该使用应用程序/ JSON 响应内容类型在这种情况下。

您可以编写一个自定义操作结果以实现:

 公共类FileJsonResult:JsonResult
{
    公共FileJsonResult(对象数据)
        :基地()
    {
        数据=数据;
        JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    }    公共覆盖无效的ExecuteReuslt(ControllerContext上下文)
    {
        context.HttpContext.Response.Write(&所述; textarea的>中);
        base.ExecuteResult(上下文);
        context.HttpContext.Response.Write(&下; / textarea的>中);
        context.HttpContext.Response.ContentType =text / html的;
    }
}

和则:

  [HttpPost]
公共虚拟的ActionResult StartImport(ImportModel模型= NULL)
{
    如果(型号!= NULL)
    {
        VAR状态= _importService.StartImport(模型);
        返回新FileJsonResult(状态);
    }
    新FileJsonResult(新{状态=假的errorMessage =该模型为空});
}

现在,你可能还需要调整您的成功处理剥去< TextArea> 标签:

  $('#frmImport')。当作ajaxForm({
    成功:函数(responseHtml){
        VAR responseHtml = responseHtml
            .replace(/ \\&下; textarea的\\> / I,'')
            .replace(/ \\&下; \\ / textarea的\\> / I,'');
        VAR响应= $ .parseJSON(responseHtml);
        //做一些与响应
    }
});

When I try and upload a file using ASP.NET MVC it works fine in FF && Chrome, but in IE and Opera a dialog pops-up which asks me to either download, save or cancel.

Choosing either of the options, prevents the fileupload from working. How can I get round this problem?

 public class ImportModel
    {                     
        [Required]
        [FileExtensions("csv", ErrorMessage = "Please upload a valid .csv file")]
        public HttpPostedFileBase File { get; set; }
    }



[HttpPost]
    public virtual ActionResult StartImport(ImportModel model = null)
    {
        if (model != null)
        {
            var status = _importService.StartImport(model);
            return Json(status, JsonRequestBehavior.AllowGet);
        }
        return null;
    }

View code below (summarised):

<div id="dlgImport" class="hidden">

        @using (Html.BeginForm(MVC.Import.StartImport(), FormMethod.Post, new { @class = "smallForm", id = "frmImport", enctype = "multipart/form-data" }))
        {            
            <div class="fields-inline">
                <div class="editor-label">
                    @Html.Label("File")
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(x => x.File, new { @class="input-file", type = "file" })
                    @Html.ValidationMessageFor(x => x.File)
                </div>              
            </div>
        }
    </div>

</div>



$(function() {
        $("#frmImport").ajaxForm({
            success: function (responseHtml) {
                // response is wrapped in pre tags by the browser - the ajax upload is carried out using an iframe                                                
                var response = $.parseJSON($(responseHtml).text());
            }
        });
});


 var vm = {

        startImport: function () {

            if ($("#frmImport").valid()) {                
                $("#frmImport").submit();
            }
        }

    }

解决方案

Now that you have posted your code it looks like that you are using the jquery form plugin. As explained in the documentation this plugin supports file uploads using AJAX but you cannot return JSON from your server side script:

Since it is not possible to upload files using the browser's XMLHttpRequest object, the Form Plugin uses a hidden iframe element to help with the task. This is a common technique, but it has inherent limitations. The iframe element is used as the target of the form's submit operation which means that the server response is written to the iframe. This is fine if the response type is HTML or XML, but doesn't work as well if the response type is script or JSON, both of which often contain characters that need to be repesented using entity references when found in HTML markup.

To account for the challenges of script and JSON responses, the Form Plugin allows these responses to be embedded in a textarea element and it is recommended that you do so for these response types when used in conjuction with file uploads. Please note, however, that if there is no file input in the form then the request uses normal XHR to submit the form (not an iframe). This puts the burden on your server code to know when to use a textarea and when not to.

So basically your upload controller action should respond with:

<textarea>{"foo":"bar"}</textarea>

instead of:

{"foo":"bar"}

Also you should not use the application/json response content type in this case.

You could write a custom action result to achieve that:

public class FileJsonResult : JsonResult
{
    public FileJsonResult(object data)
        : base()
    {
        Data = data;
        JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.Write("<textarea>");
        base.ExecuteResult(context);
        context.HttpContext.Response.Write("</textarea>");
        context.HttpContext.Response.ContentType = "text/html";
    }
}

and then:

[HttpPost]
public virtual ActionResult StartImport(ImportModel model = null)
{
    if (model != null)
    {
        var status = _importService.StartImport(model);
        return new FileJsonResult(status);
    }
    new FileJsonResult(new { status = false, errorMessage = "The model was null" });
}

Now you might also need to adapt your success handler to strip the <textarea> tags:

$('#frmImport').ajaxForm({
    success: function (responseHtml) {
        var responseHtml = responseHtml
            .replace(/\<textarea\>/i, '')
            .replace(/\<\/textarea\>/i, '');
        var response = $.parseJSON(responseHtml);
        // do something with the response
    }
});

这篇关于我如何prevent IE在asp.net mvc的文件上传使用时保存文件对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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