【问题标题】:Save base64 to image / video on Digital Ocean spaces将 base64 保存到数字海洋空间上的图像/视频
【发布时间】:2021-04-25 14:45:53
【问题描述】:

我正在使用数字海洋空间。我在 GitHub 上找到了Spaces-API。现在它提供了使用以下代码上传文件的选项,我可以上传图片了。

要求:从客户端 clide,我将使用 Ionic 传递 base64。我想知道如何通过并将其保存为 JPEG。

<?php
require_once("spaces.php");
$my_space = Spaces("M6Z255BGH6RROB5EUB3O", "vXF4XhpZ7/OyBINQaDNXex4DLuR/cBPDjfARhoSLB2A")->space("pbro", "fra1");

//Upload some text.
$my_space->upload("Super cool content", "example1.txt");

//Upload some image.
$my_space->uploadFile("img.png", "img_1.png");

//Uploaded!
?>

【问题讨论】:

    标签: php ionic-framework digital-ocean


    【解决方案1】:

    选项 1:

    使用 `upload` 方法并将图像内容作为文本传递,但首先对其进行解码:
    $my_space->upload(base64_decode($encodedImage), 'img.jpg')
    
    罢工>

    这不起作用,因为 Spaces 将以这种方式上传的文件视为文本文件,并以 application/octet-stream 标头返回它们。

    选项 2:

    首先将解码后的内容转储到临时文件,因此您可以检查图像是否有效并在推送到空间之前对其进行处理,例如:

    $filepath = tempnam(sys_get_temp_dir(), 'spacesupload');
    file_put_contents($filepath, base64_decode($encodedImage));
    
    // process file here
    
    $my_space->uploadFile($filepath, "img_1.png");
    
    // remove uploaded file from server
    unlink($filepath);
    

    注意

    可能不是文件内容,而是从前端传递到后端的数据格式为data:image/gif;base64,[encoded string]。在这种情况下,您只需要获取编码字符串才能推送到空格,例如:

    $encodedString = explode('base64,', 'data:image/gif;base64,[encoded string]', 2);
    if (count($encodedString) !== 2) {
        throw new \RuntimeException('Invalid encoded image string');
    }
    
    $encodedImage = $encodedString[1];
    
    // proceed with upload
    // ...
    

    【讨论】:

    • 图片上传有问题 - 当我从直接链接打开图片时,它会下载而不是打开,我发现原因 - Content-Type application/octet-stream ,我认为应该是 Content-Type image/pngContent-Type image/jpg ,我该怎么做管理这个?
    • 请注意:我使用的是选项 1
    • 我不太了解空格,抱歉。但我怀疑 Ionic 可能不仅会发送编码的图像内容,还会发送 mime 类型。格式为data:image/gif;base64,[encoded string]。在这种情况下,您只需要获取编码字符串即可推送到 Spaces
    • 当前用于测试我只是直接在PHP 中进行硬编码,目前不使用Ionic,我没有添加data:image/gif;base64,,这是我正在做的$my_space-&gt;upload(base64_decode("iVBORw0......,但即使在添加之后这不起作用
    • Spaces 可能不允许您将图像作为字符串上传。尝试选项 2。如果可行,我会更新我的答案
    【解决方案2】:

    您需要在参数中发送base64ecoded文件及其扩展名,以便您可以轻松将该文件写入其原始扩展名,并且您可以使用这样的通用函数

    function createImageFromBase64($data,$folder,$file) {
    
       if (!file_exists($folder)) {
          mkdir($folder, 0755, true);
       }
    
       list($type, $data) = explode(';', $data);
       list(, $data)      = explode(',', $data);
       //Note you only need this if you're sending base64 along with it's native 
       //delimeters otherwise you can skip above two lines.
       $data               = base64_decode($data);
    
       file_put_contents($folder.'/'.$file, $data); }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-02
      • 2020-07-11
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 2018-06-10
      相关资源
      最近更新 更多