0

I am doing form serialization to send the file name to the server. This serialization values is empty . I am expecting the file name over here.

My form is having a html file upload element. Which shows the file name in the right side when you select the file.

HTML:
    <form name="MyForm" id="MyForm" method="post" action=cgi_path">
    <input type="file" name="filename" id="my_file">
    </form>  

SCRIPT:
    var frm_data = $("#MyForm").serialize(); // This is empty
        $.ajax(
            {
                type: "POST",
                url: "file upload cgi url",
                data: frm_data
            });
  1. How to take the file name with out serializing this form?
  2. Is there any problem with form serialization for file name?

Thanks

JavaUser
  • 25,542
  • 46
  • 113
  • 139

3 Answers3

1

Files can only be uploaded with AJAX by using FormData, not serialisation (since you are sending more than just the filename).

$.ajax({
    url: url,
    data: new FormData($("#MyForm").get(0)),
    processData: false,
    contentType: false,
    type: 'POST'
})
Tim
  • 2,968
  • 5
  • 29
  • 55
  • What exactly is empty? Is your (I assume) MVC method receiving null? How are you receiving this request? – Tim Jan 26 '16 at 10:04
  • When i keep the debug there . the new Formdata{} is shown as empty. – JavaUser Jan 26 '16 at 10:05
  • My only guess is that the form element is malformed from the lack of opening quote (") on the action. – Tim Jan 26 '16 at 10:29
0

I assume you have an <input id="some_ID" name="some_name" type="file" />

so, you just need to pick the element "content"

var file = {}
$('#some_ID').change(function(){
    file.content = this.files[0];
    file.name = file.name;
    file.size = file.size;
    file.type = file.type;
});

then you just need to post it to the server.

0

You don't have to serialize the form to get the file name. To retrieve it just call

var filename = document.getElementById("my_file").files[0];

or this with jQuery

var filename = $('#my_file')[0].files[0]
HoangND
  • 398
  • 2
  • 12