【问题标题】:How to upload base64 image on codeigniter如何在codeigniter上上传base64图片
【发布时间】:2022-12-07 02:33:54
【问题描述】:

我正在使用 php,我在 api 中获取 Base64 图像,我想保存/存储 进入数据库并想将图像上传到服务器,我该怎么做? 我尝试使用以下代码但出现以下错误 “无法打开内容,Http writer 不支持可写连接”

function imageupload()
{
     $data = json_decode(file_get_contents("php://input"), TRUE);
     $files=file_get_contents($_FILES["file"]["tmp_name"]); 
     $image = base64_decode($files);
     $image_name = md5(uniqid(rand(), true));
     $filename = $image_name . '.' . 'png';
     $path = base_url().'upload/blog/';
     file_put_contents($path . $filename, $image);
}

【问题讨论】:

  • 你在哪一行收到错误?
  • @JacobMulquin 在最后一行 (file_put_contents($path . $filename, $image))
  • 发生这种情况是因为您使用 base_url() 定义了 $path,您应该引用文件系统中的某处,而不是面向公众的网页
  • @JacobMulquin 现在图像正在下载,但每当我尝试打开图像时,它显示“不支持文件类型”
  • 为什么要上传 base64 编码的图像?如果您正在进行普通文件上传,则可以“按原样”上传它们。通过对它们进行 base64 编码,你无缘无故地增加了大约 33% 的文件大小 + 你需要在服务器上再次解码它们。你确定所有图片都是 PNG 格式的吗?

标签: php image codeigniter model-view-controller


【解决方案1】:

看看这是否对你有帮助

查询:

$(document).on('click', '#upload', function () {
    let form_data = new FormData();
    let data_url = document.getElementById('my_image').toDataURL('image/png');
    data_url = data_url.replace(/^data:image/(png|jpg|jpeg);base64,/, '');
    form_data.append('uploaded_image', data_url);
    $.ajax({
        url: 'upload-avatar',
        method: 'post',
        data: form_data,
        dataType: 'json',
        contentType: false,
        async: true,
        processData: false,
        cache: false
    });
});

PHP:

$img = $this->request->getPost('uploaded_image'); // for ci4
$img = $this->input->post('uploaded_image'); // for ci3
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$file_data = base64_decode($img);
file_put_contents(/* my_path */, $file_data);

【讨论】:

    猜你喜欢
    • 2013-06-23
    • 2017-09-16
    • 2013-08-23
    • 2011-06-08
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多