PHP,使用 javascript 进行图像预览并通过 PHP 上传

我编写了 PHP 脚本来在上传图像之前预览图像,该脚本简单易读。第一部分是显示图像,然后在按“提交”按钮后上传图像。我在上传图片时遇到问题,无法上传。


<?php

if (!empty($_POST["uploadForm"])) {

if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {

    $targetPath = "uploads/".$_FILES['userImage']['name'];

    if (move_uploaded_file($_FILES['userImage']['tmp_name'], $targetPath)) {

        $uploadedImagePath = $targetPath;

    }

  }

}

?>

<input type="file" accept="image/*" onchange="loadFile(event)">

<img id="userImage" />

<script>

var loadFile = function(event) {

    var output = document.getElementById('userImage');

    output.src = URL.createObjectURL(event.target.files[0]);

    output.onload = function() {URL.revokeObjectURL(output.src) } // free memory

};

</script>

<form id="uploadForm" action="" method="post" enctype="multipart/form-data">

   <input type="submit" name="upload" value="Submit" class="btnSubmit">

</form>


收到一只叮咚
浏览 89回答 2
2回答

慕码人2483693

您的 PHP 代码和 HTML 中存在多个逻辑错误。检查表单提交时,您必须检查“上传”(提交按钮的名称)是否在 $_POST 中。文件上传输入应位于 <form> 标记内。为文件上传字段设置一个名称,我将其设置为“userImageUpload”,这样您就可以从 PHP 中的 $_FILES 访问它。这是最终的代码:<?phpif (!empty($_POST["upload"])) {&nbsp; &nbsp; if (is_uploaded_file($_FILES['userImageUpload']['tmp_name'])) {&nbsp; &nbsp; &nbsp; &nbsp; $targetPath = "uploads/" . $_FILES['userImageUpload']['name'];&nbsp; &nbsp; &nbsp; &nbsp; if (move_uploaded_file($_FILES['userImageUpload']['tmp_name'], $targetPath)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $uploadedImagePath = $targetPath;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}?><img id="userImage" /><script>&nbsp; &nbsp; var loadFile = function(event) {&nbsp; &nbsp; &nbsp; &nbsp; var output = document.getElementById('userImage');&nbsp; &nbsp; &nbsp; &nbsp; output.src = URL.createObjectURL(event.target.files[0]);&nbsp; &nbsp; &nbsp; &nbsp; output.onload = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; URL.revokeObjectURL(output.src)&nbsp; &nbsp; &nbsp; &nbsp; } // free memory&nbsp; &nbsp; };</script><form id="uploadForm" action="" method="post" enctype="multipart/form-data">&nbsp; &nbsp; <input type="file" accept="image/*" onchange="loadFile(event)" name="userImageUpload">&nbsp; &nbsp; <input type="submit" name="upload" value="Submit" class="btnSubmit"></form>注意:请确保“上传”文件夹已存在并且权限也正确。

慕雪6442864

您已将输入放在表单之外,但它应该在其中:<form id="uploadForm" action="" method="post" enctype="multipart/form-data">&nbsp; &nbsp;<input type="file" accept="image/*" onchange="loadFile(event)">&nbsp; &nbsp;<input type="submit" name="upload" value="Submit" class="btnSubmit"></form>
打开App,查看更多内容
随时随地看视频慕课网APP