gpt4 book ai didi

javascript - 如何使用 php 有效地将巨大的 javascript 字符串存储到文件中?

转载 作者:行者123 更新时间:2023-11-28 06:50:31 28 4
gpt4 key购买 nike

我有一个使用 逐帧生成 gif 的网站和 。简而言之,流程是:

  1. 使用 JavaScript 生成帧(存储为长的 Base64 编码字符串)
  2. 发送此字符串到 writeToFile.php,这将打开部分完整的文件并将该字符串添加到文件末尾。
  3. 等待成功写入文件,然后转到步骤 1 处理下一帧

因此,作为最后,我将逐 block 创建一个文件,其中按顺序包含 gif 的所有帧。大多数时候它都有效。然而,有时两个帧会互换,这会导致 gif 出现卡顿(例如,当球击中 this gif 中的门柱时)。

我使用 php 调用将其拼凑在一起,并等待它们成功。根据我对ajax成功事件的理解,代码应该等到上一帧保存完成后再生成下一帧,那么php怎么可能写入文件out顺序?

我尝试在ajax请求中将async设置为false,但仍然出现卡顿(尽管不太常见)。最重要的是,生成速度较慢,因此这不是我理想的解决方案。

Javascript

//Dostep - The first part of the frame generation. If we aren't done saving to file, wait 100 ms then check again
//This waits until the last frame is generated before generating a new one
var step=(function(){
var doStep = function () {
if (frameSavingToFile){ //Check
setTimeout(
function(){
doStep();
},
100 //if we are saving to file, wait
);
return;
}
//there is code here I've omitted which moves to the next frame, and stores the string
saveFrameToFile(frame);
}
return function () {
if (!stepping) setTimeout(doStep, 0);
};

}

function saveFrameToFile(theEncoder,isLastFrame){
frameSavingToFile=1;
var toAppend=window.btoa(theEncoder.stream().getData()); //add in the base 64 to the file
//save it to a file, on success set frameSavingToFile to 0
var toPassIn={'fileName':tmpFileName+".gif",'contents':toAppend};
$.ajax({
url: "php/writeToFile.php",
type: "POST",
data: toPassIn,
success: function(results) {
console.log(results);
frameSavingToFile=0;//we are no longer saving to file
if (isLastFrame){//this is set to 1 on the last frma
generationComplete();//don't generate more frames, load the gif for viewing
return;
}
}
});


}

PHP - writeToFile.php

打开文件,附加框架的内容,然后关闭

<?php
$data = $_POST['contents'];
$fileName = $_POST['fileName'];
$data = base64_decode($data);//puts it in a format I can store
$myfile = fopen('path/to/file/'.$fileName, "a") or die("Unable to open file!");
fwrite($myfile, $data);
fclose($myfile);

?>

最佳答案

代码过于复杂,有超时循环之类的。为什么不简单地重新调用 ajax 调用的成功处理程序来开始下一次写入?

例如

function savedata() {
var toAppend=window.btoa(theEncoder.stream().getData()); //add in the base 64 to the file
if (toAppend != '') { // or whatever it takes to see if the encoder's done
$.ajax(
blah blah blah,
success: savedata // keep "looping" until there's nothing left to do
);
} else {
console.log('done');
}
}

这样你就可以不断地发出ajax请求,直到没有更多的数据可以保存,一切就“结束”了。您还可以保证在上一个调用完成之前下一个调用不会出去。在不等待超时结束的情况下,每次调用还可节省高达约 99 毫秒的时间。

关于javascript - 如何使用 php 有效地将巨大的 javascript 字符串存储到文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32994651/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com