如何在服务器上传文件后创建回调?
我想在JS函数调用后在服务器上上传文件。
我想调用函数addDownload
,在此函数完成后,调用下一个javascript函数。我怎么能这样做?
我有以下源代码:
HTML:
<form id="imageform" method="post" enctype="multipart/form-data" action="actions/downloadsadd.php">
<strong>File: </strong><input name="photoimg" id="photoimg" style="width: 100px;" type="file" />
Select Image: <br />
<div id="divPreview"></div>
</form>
使用Javascript:
addDownload: function ()
{
$("#divPreview").html('');
$("#divPreview").html('<img src="Images/loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#divPreview'
}).submit();
},
PHP - downloads.php:
public function addDownloads() {
$db = new DB();
$db->connect();
$path = "../../images/upload/files/";
$valid_formats = array("php", "phtml", "php3", "php4", "js", "shtml", "pl", "py", "html", "exe", "bat", "htm", "sql");
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if (strlen($name)) {
list($txt, $ext) = explode(".", $name);
if (!in_array($ext, $valid_formats)) {
if ($size < (1024 * 1024)) { // Image size max 1 MB
$actual_image_name = time() . "." . $ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if (move_uploaded_file($tmp, $path . $actual_image_name)) {
$arr = array(
'file' => $actual_image_name
);
dibi::query('INSERT INTO [downloads]', $arr);
echo "FILE:" .$actual_image_name;
}
else
echo "Failed upload!";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
}
}
答案 0 :(得分:6)
猜猜,但您的代码似乎使用了jQuery form plugin:
$("#imageform").ajaxForm(...);
该插件允许您使用success
选项添加回调函数。当AJAX请求(即您正在调用的PHP文件中的所有代码)成功完成时,将调用此函数。
$("#imageform").ajaxForm({
target: '#divPreview',
data: {
var1: $("#inputText").val() //assuming #inputText is a text field
},
success: function() {
alert("Callback!");
}
}).submit();
有关详细信息,请参阅documentation。
答案 1 :(得分:0)
我确实喜欢上传头像。
<script type="text/javascript">
$('input[id=lefile]').change(function() {
$('#photoCover').val($(this).val());
});
function doUpload(){
//Use FormData to get files in form.
var formData = new FormData($("#myform")[0]);
$.ajax({
url: $('#myform').attr('action'),
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
},
error: function (returndata) {
alert(returndata);
}
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="avatar-content">
<form id="myform" action="http://www.example.com/editor/" method=post enctype=multipart/form-data>
<input id="lefile" type="file" name="file" style="display:none">
<div class="input-append">
<input id="photoCover" type="text" class="form-control" style="height:34px; width: 54%; display: inline-block;" onclick="$('input[id=lefile]').click();">
<div class="btn btn-primary btn-file" onclick="doUpload()">
<i class="fa fa-upload"></i> Upload
</div>
</div>
</form>
</div>