php - 我需要将文件另存为 name_01,name_02
问题描述
您好我需要将图像名称保存为 name_01,name_02 但我尝试了 5 个多小时我无法摆脱这个请检查代码并帮助我
if ($typeMessage == 'image') {
$responseMedia = $bot - > getMessageContent($idMessage);
if ($responseMedia - > isSucceeded()) {
// getRawBody() binary
$dataBinary = $responseMedia - > getRawBody(); // return binary
// get file type from header
$fileType = $responseMedia - > getHeader('Content-Type');
if (preg_match('/image/', $fileType)) {
list($fileType, $ext) = explode("/", $fileType);
$ext = ($ext == 'jpeg' || $ext == 'jpg') ? "jpg" : $ext;
if (!file_exists($fileFullSavePath)) {
$counter = 1;
$fileNameSave = 'lamsam_'.$counter.
".".$ext;
else if (file_exists($fileFullSavePath)) {
$counter++;
$fileNameSave = 'lamsam_'.$counter.
".".$ext;
}
}
}
$botDataFolder = 'LAMSAM PAPER/'; // main save file folder
$botDataUserFolder = $botDataFolder.$sourceType.$sourceId; // sub folder= sourceId
if (!file_exists($botDataUserFolder)) { // check if don't have folder sourceId
mkdir($botDataUserFolder, 0777, true);
}
// path
$fileFullSavePath = $botDataUserFolder.
'/'.$fileNameSave;
file_put_contents($fileFullSavePath, $dataBinary);
我期待输出
- lamsam_01.jpg
- lamsam_02.jpg
但实际只是
- lamsam_01.jpg
解决方案
首先,我们看不到任何循环,因此$counter
不太可能影响任何事情,除非您如下所示循环遍历它。
您可以打开一个文件 ( fopen()
),然后fwrite()
向其中写入 ( ) 数据。将数据写入其中后,您需要关闭 ( fclose()
) 文件:
$fp = fopen('file.txt', 'a+'); //Append mode
// $fp = fopen('file.txt', 'w'); //Write mode
fwrite($fp, $data);
fclose($fp);
fopen()
:https ://www.php.net/manual/en/function.fopen.php
fwrite()
:https ://php.net/manual/en/function.fwrite.php
fclose()
:https ://www.php.net/manual/en/function.fclose.php
在一个循环中:
这将遍历所有图像,并创建您需要的命名约定:
从 1开始,$i
所以应该$i
小于或等于$noOfFiles
继续有了它,我看不到你将如何增加。loop
$_SESSION
counter
$counter
for($i = 1; $i <= $noOfFiles; $i++) {
$fp = fopen('lamsam_' . $i .'.jpg', 'w');
fwrite($fp, $data[$i]);
fclose($fp);
}
lamsam_1.jpg
等lamsam_2.jpg
。
您将需要计算$noOfFiles
for 循环,并在$data
数组中包含图像的数据。
编辑回复更新
您需要将所有图像文件数据(即每个图像)存储在$dataBinary
. 所以$dataBinary
需要是一个数组:
$dataBinary = array(
$image1BinaryData,
$image2BinaryData,
$image3BinaryData,
$image4BinaryData,
$image5BinaryData,
$image6BinaryData,
$image7BinaryData,
$image8BinaryData,
$image9BinaryData
$image10BinaryData
);
所以..如果您使用 获取图像$responseMedia->getRawBody()
,那么您要么希望它作为一个数组出现(如果你得到相同的图像,它似乎只得到一个图像)......或者你也想要循环通过任何可用的方法来获取您所追求的所有图像并将它们添加到数组中。
然后在您的循环中,使用数组$i
的索引$dataBinary
,您还可以循环浏览要添加到每个文件的图像,而不仅仅是创建 10 个名称不同但图像相同的文件:
for($i = 0; $i <= $num_files;) {
$i++;
$fp = fopen('lamsam_' . $i .'.jpg', 'w');
fwrite($fp, $dataBinary[$i]);
fclose($fp);
$fp = $fileNameSave;
}
推荐阅读
- azure - Azure IoT 中心 - 启用路由时,IoT 中心触发器不执行
- react-native - 需要在完成之前获得将要完成的照片的大小。世博会
- json - 在这种情况下,使用 JSON 数据的更好方法是什么?
- ios - 如何将 IOS 14 支持添加到我的 React Native 应用程序?
- vb.net - 如何在 Visual Basic 中输入变量的范围
- rust - Rust 将 trait 的实现依赖注入到另一个对象中
- c++ - 在 C++ 中为不同对象的集合提供接口的最简洁方法
- javascript - Alpine.js +flatpickr Datetimepicker 不工作
- python - 在二维列表中查找最高平均值
- f# - 如何使用 F# 验证 RsaSha256 JWT 签名?