【发布时间】:2015-01-01 22:54:42
【问题描述】:
我正在尝试使用 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 的情况下不起作用?
【问题讨论】:
-
Ajax 文件上传 - stackoverflow.com/questions/26674575/…
-
尝试在您的 jQuery.Ajax() 调用中设置
contentType: 'multipart/form-data'。此外,您需要向data提供一个FormData对象 -
我尝试添加 contentType: 'multipart/form-data',它也不起作用。结果相同。正在创建文件。但大小为 0。
标签: javascript jquery ajax perl image-uploading