如何通过AJAX和PHP解码和上传GIF [英] How to decode and upload GIF via AJAX and PHP
问题描述
我目前正在使用Gifshot.js在我的网站上创建用户头像.我希望能够存储GIF文件服务器端,但是无法使其正常工作.问题是如何正确解码base64编码的GIF文件,以通过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));
推荐答案
您可以POST
服务器上文件对象的Blob
表示形式,并使用php://input
和fopen()
在php
处获取文件内容,请参见尝试通过以下方式传递ToDataURL:使用输入类型文本超过524288个字节.
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));
您可以通过将Blob
转换为ArrayBuffer
,创建以ArrayBuffer
作为参数的TypedArray
(例如Uint8Array
)并将文件流式传输到服务器,将文件作为块流式传输到服务器.服务器使用WebSocket
.
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
.
这篇关于如何通过AJAX和PHP解码和上传GIF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!