【问题标题】:How to Upload Files in MVC [duplicate]如何在 MVC 中上传文件 [重复]
【发布时间】:2012-10-08 01:52:16
【问题描述】:

可能重复:
File Upload ASP.NET MVC 3.0

我正在尝试在调试器中打印出文件的名称,以确保我得到它:

<EmployeeAuthorize()>
<HttpPost()>
Function SendNewMessage(ByVal file1 As HttpPostedFileBase) As JsonResult


    Dim fileName = Path.GetFileName(file1.FileName)
    Debug.Print(fileName)

    Return Nothing

End Function

我用这个发送数据:

var file1 = $('#file1').val();

            $(this).parent('li').hide();
            $('#pleaseWait').show();

            $.ajax({
                url: '/Message/SendNewMessage',
                type: 'post',
                data: { file1: file1 },
                dataType: 'json',
                success: function (result) {
                    // update with results
                    //alert(JSON.stringify(result));
                    $.each(result, function (i, item) {
                        // do nothing
                    });
                    $('#myDiv').html(JSON.stringify(result));

                },
                error: function (result) {
                    alert('An error occurred when updating the database.  Please contact technical support.  ');

                }
            });

它不会在我的控制台中打印任何数据。它给出了一个NullReferenceException,所以我可以假设它根本没有得到文件名。我究竟做错了什么?谢谢。

【问题讨论】:

    标签: jquery asp.net-mvc vb.net asp.net-mvc-3


    【解决方案1】:

    文件不能直接通过 ajax 上传。你应该使用 iframe 或 flash 或 jquery 特殊插件来代替它。

    例如可以通过jquery forms插件实现ajax文件上传。

    试试这个,它有效:

    Public Class MessageController Inherits System.Web.Mvc.Controller
    
        Function SendNewMessage(ByVal file1 As HttpPostedFileBase) As JsonResult
    
    
            Dim fileName = Path.GetFileName(file1.FileName)
            Debug.Print(fileName)
    
            Return Nothing
    
        End Function
    
    End Class
    

    在你看来:

    <script type="text/javascript" >
        $(function () {
            var options = {
                beforeSubmit: function (formData, jqForm, options) { },  // pre-submit callback 
                success: function (responseText, statusText, xhr, form) { }   // post-submit callback 
            };
            // bind form using 'ajaxForm' 
            $('#uploadForm').ajaxForm(options);
        });
    </script>
    
    <form action="/Message/SendNewMessage" enctype="multipart/form-data" method="post" id="uploadForm" >
        <input type="file" name="file1" />
        <input type="submit" value="send" /> 
    </form>
    

    【讨论】:

    猜你喜欢
    • 2017-09-25
    • 2015-06-03
    • 2020-03-23
    • 2019-04-30
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 2017-12-26
    • 2013-05-29
    相关资源
    最近更新 更多