【问题标题】:Uploading an image from localStorage to PHP将图像从 localStorage 上传到 PHP
【发布时间】:2015-03-10 18:59:26
【问题描述】:

首先,对不起我的英语不好。 我遇到以下问题:

我确实有以下代码将丢弃的图像存储在 localStorage 上:

localStorage.setItem("dropped_images", JSON.stringify( array_dropped_images ) );

这将导致如下所示:

localStorage.getItem('dropped_images'):
[
{"id":0,"data":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACgAAAAWgCAIAAAAdYo2IAAAAGXRFW…nu8vxl30QxDphgBbok9vXa1iT2dWMDBGQHDCyNMfCUO83/A/VzaPVq31uqAAAAAElFTkSuQmCC"},
{"id":1,"data":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACgAAAAWgCAIAAAAdYo2IAAAAGXRFW…m4r4R9wH1l7K6H+6pa8cB9IzySnR2RydqmlhaTBqfp8hP/HzkuuKqP/f8rAAAAAElFTkSuQmCC"}
]

我只是无法理解如何将它发送到 PHP 并通过 $_FILES 获取它。你能帮助我吗? 谢谢!

------- 已解决 --------------- -------------------------------------------------- ------------------------------

根据最佳答案(@sam-battat),可以解决这个问题,编辑部分功能:

function base64_to_img($base64_string, $output_file) {
    $data = explode(',', $base64_string);

    /**
     * Remove the raw text
     */
    $ext = str_replace("data:image/", '', $data[0]);
    $ext = str_replace(";base64", '', $ext);

    /**
     * Create the file with the correct extension
     */
    $ifp = fopen($output_file . "." . $ext, "wb"); 

    /**
     * Create file based on base64
     */
    fwrite($ifp, base64_decode($data[1])); 
    fclose($ifp); 

    /**
     * return file path
     */
    return $output_file; 
}

非常感谢!

【问题讨论】:

标签: javascript php file upload local-storage


【解决方案1】:

您可以发布字符串(base64 字符串)并稍后将其转换为文件:

$img = $_POST['img_data'];

$file = base64_to_img($img, '/path/to/file.png');

function base64_to_img($base64_string, $output_file) {
    $ifp = fopen($output_file, "wb"); 

    $data = explode(',', $base64_string);

    fwrite($ifp, base64_decode($data[1])); 
    fclose($ifp); 

    return $output_file; 
}

【讨论】:

  • 嗯,我想我明白了。在我看来,根据您的回答,我可以执行以下操作: data = { id: 0, data: [the string from data on my question] } $.post( 'request', data, function ... } 然后在 PHP 中我会像你说的那样进行转换。对吗?
猜你喜欢
  • 2014-08-26
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-02
相关资源
最近更新 更多