Image uploader not working with JQuery/ajax

蓝咒 提交于 2019-12-11 08:24:44

问题


I am trying to upload a file on server using Ajax and jquery and perl is scripting language.

This is the code for selecting a file.

<input id="avatar" type="file" name="avatar" />
<button type='button' id='fileUpload' class='btn btn-primary btn-sm'>
      <span class='glyphicon glyphicon-upload'></span> 
      Start Upload
</button>

And this is the code for calling upload script using jquery.

$('#fileUpload').click(function() 
{

    alert ('reached here');
    var file_data = $("#avatar").prop("files")[0]; // Getting the properties of file from file field
    var form_data = new FormData(); // Creating object of FormData class
    form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data

    $.ajax({
        url: "upload.pl",
        dataType: 'html',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data, // Setting the data attribute of ajax with file_data
        type: 'post',
        success : function(response)
        {
            alert ("success");
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) 
        { 

          alert ("script error");


        }, // error 
    });
});

Image file is getting created on the server but size is empty.

I'm sure there is no issue in upload.pl because if i m using form to upload image then its working fine and image file with exact size is getting saved on the server.

<form action="upload.pl" method="post" enctype="multipart/form-data">
        <p>Photo to Upload: <input type="file" name="avatar" /></p>
        <p><input type="submit" name="Submit" value="Submit Form" /></p>
    </form>

Can please someone help me why it is not working in case of Ajax/jquery?


回答1:


The value of the name parameter is file in your AJAX request but avatar in your regular form request. You can verify this using the developer tools for your favorite browser and inspecting the requests. You haven't shown your Perl code, but this is almost certainly the cause of your issue.

As proof, I was able to successfully upload a file using your JavaScript code and the following CGI script (based on the documentation for processing a file upload):

use strict;
use warnings;

use CGI;

my $q = CGI->new;

my $lightweight_fh = $q->upload('file');

if (defined $lightweight_fh) {
    # Upgrade the handle to one compatible with IO::Handle:
    my $io_handle = $lightweight_fh->handle;

    open my $out_fh, '>>', 'file' or die "Failed to open file: $!";

    my $buffer;
    while (my $bytesread = $io_handle->read($buffer,1024)) {
        print $out_fh $buffer;
    }
}

print $q->header,
      $q->start_html,
      $q->p('Success'),
      $q->end_html;


来源:https://stackoverflow.com/questions/26762446/image-uploader-not-working-with-jquery-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!