我希望用户上传到我网站的图片减少文件大小。我有以下脚本,但我无法找出为什么我的图片不会显示在我的"上传"文件夹中。
当我上传图片时,我会转到" upload.php"页。
我犯了什么错误,或者我忘记了什么?
这是我的HTML代码:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/code.js"></script>
</head>
<form enctype="multipart/form-data" method="post" action="upload.php">
<div class="row">
<label for="fileToUpload">Select Files to Upload</label><br />
<input type="file" name="filesToUpload[]" id="filesToUpload" multiple="multiple" />
<output id="filesInfo"></output>
</div>
<div class="row">
<input type="submit" value="Upload" />
</div>
</form>
<script>
function fileSelect(evt) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
document.getElementById('filesToUpload').onchange = function(){
var files = document.getElementById('filesToUpload').files;
for(var i = 0; i < files.length; i++) {
resizeAndUpload(files[i]);
}
};
} else {
alert('The File APIs are not fully supported in this browser.');
}
function resizeAndUpload(file) {
var reader = new FileReader();
reader.onloadend = function() {
var tempImg = new Image();
tempImg.src = reader.result;
tempImg.onload = function() {
var MAX_WIDTH = 600;
var MAX_HEIGHT = 450;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH) {
if (tempW > MAX_WIDTH) {
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
} else {
if (tempH > MAX_HEIGHT) {
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(ev){
document.getElementById('filesInfo').innerHTML = 'Done!';
};
xhr.open('POST', 'upload.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = 'image=' + dataURL;
xhr.send(data);
}
}
reader.readAsDataURL(file);
}
document.getElementById('filesToUpload').addEventListener('change', fileSelect, false);
</script>
这是我使用的PHP代码:
<?php
if ($_POST) {
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
}
答案 0 :(得分:2)
如果您正在上传文件并且它们位于{{1}中,那么在您上传文件时,您应该使用$_FILES['image']
代替$_POST['image']
来解读您的问题。数组。
可以与$_FILES
一起使用的最简单的PHP脚本是
javascript
当您使用if (isset($_FILES['image'])) {
// Example:
move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR . $_FILES['image']['name']);
exit;
}
时,它也会有效,但需要file_put_contents
数组中的文件不是$_FILES
。
您可以在 $_POST
标题下看到教程HERE
,甚至可以添加拖放功能。丢弃功能。