Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - How to decode and upload GIF via AJAX and PHP

I'm currently using Gifshot.js to create user avatars on my site. I want to be able to store the GIF files server side, but am unable to get it to work. The question is how do I properly decode a base64 encoded GIF file, to store via PHP? Also, is there a way to upload the files as incremented numbers, instead of a static name? Here is what I currently have for code:

Javascript:

$("#savegif").click(function(){      
    gifshot.createGIF({
        interval: 0.1,
        numFrames: 25,
    }, function (obj) {
        if (!obj.error) {

            var image = obj.image,
            animatedImage = document.getElementById('animatedgif');
            animatedImage.src = image;

            var data = animatedImage.src;
            $.ajax({ 
                url: "gifsave.php",
                method: "POST",
                dataType: "text",
                data: { data }
            });
        }
    });
});

PHP:

$file = $_POST['data'];
$img = str_replace('data:image/gif;base64,', '', $file);
file_put_contents('images/image.gif', base64_decode($img));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can POST a Blob representation of file object to server and use php://input and fopen() to get the file contents at php, see Trying to Pass ToDataURL with over 524288 bytes Using Input Type Text.

fetch("gifsave.php", {method:"POST", body:blob})
.then(response => response.ok)
.then(res => console.log(res))
.catch(err => console.error(err));

You can stream the file as chunks to server by converting a Blob to an ArrayBuffer, creating a TypedArray, for example, a Uint8Array, with ArrayBuffer as parameter, and streaming the file to server using WebSocket.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...