我正在尝试使用 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/