簡體   English   中英

在提交到PHP上傳之前,在客戶端調整圖像大小

[英]Resizing Image on client-side before submitting to PHP to Upload

嗯,你好。

我目前使用此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方法,因為它會改變整個代碼。 任何幫助都感激不盡。

提前致謝。

由於您在blob字段中有文件,因此只需使用file_put_contents函數將文件數據保存到所需的目標位置,如

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

不需要整個move_uploaded_file部分。 只需將其視為普通請求,並使用foto字段中的值來保存圖像。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM