javascript - 图像 uploader 不适用于 JQuery/ajax

标签 javascript jquery ajax perl image-uploading

我正在尝试使用 Ajax 和 jquery 在服务器上上传文件,而 perl 是脚本语言。

这是选择文件的代码。

<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 中不起作用吗?

最佳答案

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;

关于javascript - 图像 uploader 不适用于 JQuery/ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26762446/

相关文章:

javascript - 尝试对 PHP 进行 ajax POST 调用以将 SQL 查询变量返回给 jquery 时出错

javascript - HTTP500 : SERVER ERROR on aspx page only appears on edge

javascript - WordPress 插件错误。备份伙伴

javascript - CKEditor获取编辑器的内容

javascript - 仅当一系列 XHR (IO) 请求成功时,调用 YUI3 中函数的最佳方法是什么?

javascript - XMLhttprequest.send 在 PHP 中给出空白数组

javascript - jQuery 的字符串简单数学运算

javascript - d3 : drawing elements correctly but not adding new data to the dom

javascript - 在选择器初始化并在 ('close' ) 事件上使用后,是否有某种方法可以在不同的脚本中获取 amsul pickadate/pickatime 对象?

带有处理程序的backbone.js滚动事件未解除绑定(bind)