提交给PHP之前,请在客户端上调整图像大小



好吧,你好。

我目前正在此处使用此JavaScript库来调整客户端的图像大小。我已经通过此代码成功地在客户端上调整了图像:

document.getElementById('foto_select').onchange = function(evt) {
  ImageTools.resize(this.files[0], {
    width: 623, // maximum width
    height: 203 // maximum height
  }, function(blob, didItResize) {
    // didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
    document.getElementById('preview').src = window.URL.createObjectURL(blob);
    var hidden_elem = document.getElementById("foto");
    hidden_elem.value = window.URL.createObjectURL(blob);
    // you can also now upload this blob using an XHR.
  });
};
<script src="https://gist.githubusercontent.com/dcollien/312bce1270a5f511bf4a/raw/155b6f5861e844310e773961a2eb3847c2e81851/ImageTools.js"></script>
<form action="save.php?p=edit_headline" method="post" enctype="multipart/form-data">
<div align="center">
  <input type="file" id="foto_select" name="foto_select" />
  <input type="hidden" id="foto" name="foto" />
  <div class="spacer-20"></div>
  Preview : <br/>
  <img id="preview" width="240" height="240" />
</div>
</form>

好吧,图像已成功上传并在客户端上调整大小。但是问题是我需要将存储在客户端表单上的文件提交到PHP服务器端处理中。BLOB数据存储在称为foto的隐藏输入中。

这是我的php代码:

<?php
    $imgFile = $_FILES['foto']['name'];
    $tmp_dir = $_FILES['foto']['tmp_name'];
    $imgSize = $_FILES['foto']['size'];
    $upload_dir = '../admin/images/headline/'; // upload directory
    $imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
    // valid image extensions
    $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
    // rename uploading image
    $photo = rand(1000, 1000000) . "." . $imgExt;
    // allow valid image file formats
    if (in_array($imgExt, $valid_extensions)) {
        // Check file size '5MB'
        if ($imgSize < 5000000) {
            move_uploaded_file($tmp_dir, $upload_dir . $photo);
        } else {
            $errMSG = "Sorry, your file is too large.";
            echo "<script>alert('File foto terlalu besar'); window.location ='berita.php' </script>";
        }
    } else {
        $errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    }
    if (empty($imgFile)) {
        $photo_save = $foto_old;
    } else {
        $photo_save = $photo;
        unlink("images/headline/". $foto_old); // upload directory
    }
    $query = mysqli_query($con, "UPDATE `headline` SET `photo` = '$photo_save' WHERE `id` = '$id'");
    if ($query) {
        echo "<script>alert('Headline Updated'); window.location ='index.php' </script>";
    } else {
        echo "<script>alert('Failed'); window.location ='index.php' </script>";
    }
?>

该照片已在MySQL数据库中进行了更新,但是该文件未从客户端输入表单复制到服务器文件夹目标。

我需要有关此问题的帮助,我可能会避免使用usng xhr/ajax方法,因为它会更改整个代码。任何帮助将不胜感激。

预先感谢。

由于您在blob字段中有文件,只需使用 file_put_contents函数将文件数据保存到所需的目标,例如

file_put_contents('/path/to/new/file_name', $_POST['foto']);

不需要整个move_uploaded_file部分。只需将其视为正常请求,然后使用foto字段中的值保存图像。

最新更新