图片上传器不使用JQuery / ajax

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

这是选择文件的代码。

  

这是使用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中没有问题,因为如果我使用表单上传图像,那么它的工作正常和具有确切大小的图像文件将被保存在服务器上。

 

Photo to Upload:

可以请某人帮助我为什么它不能在Ajax / jquery的情况下工作?

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

作为证据,我能够使用您的JavaScript代码和以下CGI脚本成功上传文件(基于处理文件上传的文档):

 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;