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

    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型