使用PHP中的base64编码上传多个文件

时间:2019-07-17 12:16:45

标签: php html mysql

我想上传数据库中的图像并使用base64编码/解码来获取它们。但是我不知道该怎么办?

HTML:

    <form method="POST" action="add_script.php" enctype="multipart/form-data">
    <input type="file" name="s_o_img[]" class="form-control" multiple="" accept="image/*">
    <input type="submit" name="sbtn" class="btn btn-primary" value="Save">
    </form>

PHP:

      if(isset($_POST['sbtn']))
     {
     $countfiles = count($_FILES['s_o_img']['name']);
     for($i=0;$i<$countfiles;$i++){
     $filename = $_FILES['s_o_img']['name'][$i];
     move_uploaded_file($_FILES['s_o_img']['tmp_name'][$i],$filename);
     $bin = file_get_contents($_FILES["s_o_img"]["name"]);
     $hex_string = base64_encode($bin);
     }

错误:

  

警告:file_get_contents()期望参数1为有效路径,在第14行的C:\ xampp \ htdocs \ download \ add_script.php中给出的数组

2 个答案:

答案 0 :(得分:0)

尝试这种方式

[$i]上添加file_get_contents

if(isset($_POST['sbtn']))
{
    $countfiles = count($_FILES['s_o_img']['name']);
    for($i=0;$i<$countfiles;$i++){ // add .length of $countfiles
        $filename = $_FILES['s_o_img']['name'][$i];
        move_uploaded_file($_FILES['s_o_img']['tmp_name'][$i],$filename);
        $bin = file_get_contents($_FILES["s_o_img"]["name"][$i]);  // add [$i] for valid index image
        $hex_string = base64_encode($bin);
    }
}

答案 1 :(得分:0)

$images = array('zdcci389,3232cci389,42423fsfs2343'); //all base64 image strings
foreach($images as $image){
    $binary = base64_decode($image);
    $f = finfo_open();
    $mime_type = finfo_buffer($f, $binary, FILEINFO_MIME_TYPE);
    $expload_data = explode("/",$mime_type);
    $expload_data = array_filter($expload_data);
    $extension = "jpg";
    if (!empty($expload_data)){
        $extension_val = $expload_data[1];
        if($extension_val!=""){
            $extension = $extension_val;
        }
    }
    $filename = uniqid().".".$extension;
    $orignal_path =  "uploads/".$filename;
    file_put_contents($orignal_path, $binary);
}

尝试一下,将起作用。