【发布时间】:2017-10-30 03:51:11
【问题描述】:
嗯,你好。
我目前正在使用来自 here 的这个 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 数据库中更新,但文件没有从客户端输入表单复制到服务器文件夹目标。
我在这个问题上需要帮助,我可能会避免使用 XHR / AJAX 方法,因为它会改变整个代码。任何帮助将不胜感激。
提前致谢。
【问题讨论】:
标签: javascript php jquery html ajax