javascript
  • jquery
  • ajax
  • perl
  • image-uploading
  • 2014-11-05 106 views 1 likes 
    1

    我想上传服务器上的文件使用Ajax和jQuery和Perl是脚本语言。图片上传不能使用JQuery/ajax

    这是选择文件的代码。

    <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> 
    

    这是使用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 
        }); 
    }); 
    

    图像文件正在服务器上创建,但大小为空。

    我确定upload.pl中没有问题,因为如果我使用表单上传图像,那么它的工作正常和具有确切大小的图像文件将被保存在服务器上。

    <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> 
    

    可以请别人帮我为什么它不工作的情况下的Ajax/jQuery的?

    +0

    阿贾克斯文件上传 - http://stackoverflow.com/questions/26674575/php-upload-extract-and-progressbar/26679480#26679480 – NewToJS 2014-11-05 17:03:02

    +0

    尝试在jQuery.Ajax()调用中设置'contentType:'multipart/form-data''。另外你需要提供一个'FormData'对象给''' – 2014-11-05 17:35:20

    +0

    我尝试添加contentType:'multipart/form-data',它也不起作用。同样的结果。文件正在创建。但大小为0。 – 2014-11-05 17:43:58

    回答

    0

    name参数的值在您的AJAX请求中为file,但在您的常规表单请求中为avatar。您可以使用您喜欢的浏览器的开发人员工具来验证这一点,并检查请求。你没有显示你的Perl代码,但这几乎肯定是你问题的原因。

    为了证明这一点,我能够使用JavaScript代码和下面的CGI脚本(基于为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; 
    
    相关问题