使用ASP.NET MVC使用Ajax调用上传文件 [英] Upload file using Ajax call using ASP.NET MVC

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

问题描述

我想使用以下方式在页面中上传文件:

I would like to upload a file in my page using:

<input type="file" name="FileName">

我有一个按钮,单击此按钮即可完成ajax发布.

I have a button, clicking on which an ajax post is done.

$.ajax({
           cache: false,
           async: true,
           type: "POST",
           url: '@Url.Content("~/OCR/OCRProcessor")',
           data: '',
           success: function (data) {
               $('#ocrresult').val(data);
           }
       });

我想通过控制器动作方法上传文件,如下所示:

I would like to get the file uploaded in the controller action method something like below:

HttpPostedFileBase hpf = Request.Files["FileName"] as HttpPostedFileBase 

请让我知道实现此任务的最佳方式.

Please let me know the optimal way to achieve this task.

推荐答案

jquery 表单插件(<在这种情况下,a href ="https://github.com/malsup/form/" rel ="nofollow"> GitHub链接)将是理想的选择. 您可以像这样简单地做到这一点. (包括以这种形式输入的文件)

jquery Forms plugin (GitHub Link)would be an ideal choice in this context. You can simply do it like this. (Include the file input in this form)

$('#myFormId').submit(function() { 
    // submit the form 
    $(this).ajaxSubmit(); 
    // return false to prevent normal browser submit and page navigation 
    return false; 
});

演示

这将是一种无插件"方法(仅在Html5中使用),但我仍建议该插件

This would be a No plugin approach (only in Html5), but I'm still recommending the plugin

$("#myFormId").submit(function(){

    var formData = new FormData($(this)[0]);

    $.ajax({
        url: "YourPath/ToAction",
        type: 'POST',
        data: formData,
        async: false,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });

    return false;
});

另一个不错的插件.

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

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