0

Possible Duplicate:
File Upload ASP.NET MVC 3.0

I am trying to just print out the name of the file in the debugger to make sure I am getting it this far:

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


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

    Return Nothing

End Function

I am sending the data with this:

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.  ');

                }
            });

It doesn't print any data in my console. It gives a NullReferenceException so I can assume it's not getting the filename at all. What am I doing wrong? Thanks.

Community
  • 1
  • 1
user1477388
  • 20,790
  • 32
  • 144
  • 264

1 Answers1

2

Files cannot be uploaded directly through ajax. Instead of it you should use iframe or flash or jquery special plugins.

For example you can accomplish ajax file uploading through jquery forms plugin.

Try this, it works:

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

and this in your view:

<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>
Gromer
  • 9,861
  • 4
  • 34
  • 55
testCoder
  • 7,155
  • 13
  • 56
  • 75