我试图在saveimage.php处理它们之前制作一个上传脚本,它调整了多个图像客户端的大小。原因是因为他们会在可能非常缓慢的互联网的外部位置上传。通过javascript循环上传多个画布图像
我已经能够找到这里的代码片段,这帮助我把它放在一起。我只是一个初学者,所以它可能非常混乱!
它目前的功能是检查文件是否在'file_input'字段中输入。然后它会查看文件的数量并遍历它们,直到每个文件都被放置在画布上并在其中进行上传。
但是,问题是:当我没有为每个文件添加警报时,循环速度过快,例如只处理10或10个图像中的1或2个。因为上传脚本将比使用新图像更新画布更快。
这是我当前的页面,简化为核心:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
</head>
<body>
<form>
<input id="file_input" type='file' multiple />
</form>
<div id="preview">
<canvas id="canvas"></canvas>
</div>
<script>
var input = document.getElementById('file_input');
input.addEventListener('change', handleFiles);
function handleFiles(e) {
var files = input.files;
alert(files.length +" files are being uploaded!"); // display amount of files for testing purpose
for (var i = 0; i < files.length; ++i) {
alert("Upload file number: "+i); // display file # for testing purpose, when this is removed the script will go too fast
var MAX_HEIGHT = 1000;
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image;
img.onload = function(){
if(img.height > MAX_HEIGHT) {
img.width *= MAX_HEIGHT/img.height;
img.height = MAX_HEIGHT;
}
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
preview.style.width = img.width + "px";
preview.style.height = img.height + "px";
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
// the canvas should contain an image now and this will send it through saveimage.php
var myDrawing = document.getElementById("canvas");
var drawingString = myDrawing.toDataURL("image/jpeg", 0.5);
var postData = "canvasData="+drawingString;
var ajax = new XMLHttpRequest();
ajax.open("POST",'saveimage.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.onreadystatechange=function()
{
if (ajax.readyState == 4);
}
ajax.send(postData);
};
img.src = URL.createObjectURL(e.target.files[i]);
}
}
</script>
</body>
</html>
这是我saveimage.php效果很好,但只是为完整的综述:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
$rawImage=$GLOBALS['HTTP_RAW_POST_DATA'];
$removeHeaders=substr($rawImage, strpos($rawImage, ",")+1);
$decode=base64_decode($removeHeaders);
// check if the file already exists and keep adding +1 intil it's unique
$i = 1;
while(file_exists('uploads/image'.$i.'.jpg')) {
$i++;
}
$fopen = fopen('uploads/image'.$i.'.jpg', 'wb');
fwrite($fopen, $decode);
fclose($fopen);
}
?>
一点额外信息:
- 我已经添加了画布,因为据我所知,这是 只能调整图像客户端的方式。在最后的脚本中,将 设置为隐藏。
- 如果画布可以跳过,并立即将数据发送到saveimage.php 那么我也会解决这个问题。
- 正如我所说我不是很有经验的JavaScript,所以如果有一个更简单的方法来实现这个目标。请告诉我!
在此先感谢!
在做任何事情之前:在*设置src之前设置onload handler *。 – GameAlchemist 2015-02-11 15:33:10
@GameAlchemist我已经将onload处理程序放在src之前,它似乎仍然以同样的方式运行,它的原因是什么? – Pascal 2015-02-11 16:08:09