繁体   English   中英

Ajax提交表单并检索URL

[英]Ajax to submit form and retrieve the url

我在这个上待了几个小时,我想不通,所以请帮忙。

我想做的是使用Ajax将index.php中的表单提交到upload.php并检索上载的文件URL,以便我可以显示缩略图。

然后在缩略图下方,再次出现表单以上传其他图像。 这应该持续三遍。 因为图像限制为三个。 缩略图应保留到最后。 (请看图片)

在此处输入图片说明

我的index.php

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

我的upload.php

<?php
$target_dir = "data/temp/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo $_SERVER['SERVER_NAME']."/data/temp/". basename( $_FILES["fileToUpload"]["name"]);
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

谢谢。

您可以通过Ajax做到这一点...。在直接卸载文件图像的JavaScript中,可以使用JavaScript通过Ajax做到这一点,然后从服务器端回显您的url,它将发送回您的客户端页面,在该页面上您可以使用JavaScript显示缩略图(如果您不明白,如果您需要详细的代码,请问我

//First add id to form like formid
//Next code
var formid = document.getElementById('formid');
   fileToUpload = new FormData(formid);
xhttp = new XMLHttpRequest ();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("img_id").innerHTML = this.responseText;//here img_id is id for img element where you want to show thumbnail
    }
  };
  xhttp.open("POST", "upload.php", true);// if you want to send by get method then write get inside of post
  xhttp.send(fileToUpload);

// Important !!!! form php page echo complete location of thumbnail 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM