donglian1982 2017-04-04 10:43
浏览 1253

如何从php中解码的Base64字符串中提取文件名和扩展名

I'm uploading files to my PHP webservice by encoding them to Base64 and sending them via Json.

I'm decoding the data on the server using this code: $file_content = base64_decode($file,true);

Now I want to extract file name and extension from the $file_content variable.

How can I do that?

UPDATE: here is the code I used to decode the file:

include '../conn.php';
include '../functions.php';

$entityBody = file_get_contents('php://input');
$decodedJson = json_decode($entityBody);
$user_email = $decodedJson->{'email'};
$user_token = $decodedJson->{'token'};

$file = $decodedJson->{'file'};  //This is the encoded content of the file from JSON
$file_content = base64_decode($file,true);

if(!checkStudentAuthorizationOrHigher($user_email,$user_token,$conn))
{
    die();
}

//now I want to get $file_content type (extension or MIME type) and
//file name from the $file_content
//I tried the below code but it only gets file path as input parameter and doesn't work this way

echo mime_content_type($file_content);

Only the file content is given to my PHP webservice through JSON (file name or extension is not sent to my service). If it helps, the client side of my application is both a C# Windows Forms app and an Android app.

I want to save the file on the server with the same file name as the client side. Also I have to check the file type to make sure it is allowed on the server. (the file can be .pdf , .jpg , .jpeg or .zip)

Now is there a way to extract file info from $file_content variable?

  • 写回答

1条回答 默认 最新

  • dsiy62758 2017-04-04 10:52
    关注

    I used thw Intervention/image library https://github.com/Intervention/image to deal with base64 encoded images. THis library got many other features as well.

    $imageManager = new Intervention\Image\ImageManager();
    $imageObject = $imageManager->make($base64EncodedImageSource);
    
    $imageInfo = getimagesize($base64EncodedImageSource);
    $this->mimeType = $imageInfo[2];
    $extension = image_type_to_extension($this->mimeType);
    $width = $imageInfo[0];
    $height = $imageInfo[1];
    $tempFilePath = '/path/to/file';
    $imageObject->save($tempFilePath, 100);
    

    Alternatively, if you have mime type of the file, you can use function image_type_to_extension to get file extension

    评论

报告相同问题?

悬赏问题

  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算