我们有API接收以base64字符串转换的图像。我们的移动应用程序在转换过程中消耗了太多的 RAM(到 base64),现在我们需要以多部分形式上传图像。我开发了移动部分,但我坚持使用PHP API。我们从凌空切换到改造,因为凌空不支持分段上传。
我需要在接收分段图像上传的脚本中更改哪些内容?
<?php
//header('Content-Type : bitmap; charset=utf-8');
//header('Content-Type: application/json');
if (isset($_POST["encoded_string"])) {
//encoded_string -> base64 string sent from mobile phone
$encoded_string = $_POST["encoded_string"];
$image_name = $_POST["image_name"];
$decoded_string = base64_decode($encoded_string);
$path = 'images/' . $image_name;
if (!file_exists('images')) {
mkdir('images', 0777, true);
}
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
if ($is_written > 0) {
$connection = mysqli_connect('localhost', 'root', '', 'test');
if ($connection) {
$query = "INSERT INTO photos(name,path) values('$image_name','$path');";
$result = mysqli_query($connection, $query);
if ($result) {
echo json_encode(array(
"response" => "Success! Image is succefully uploaded!.",
"result" => "success"
));
} else {
echo json_encode(array(
"response" => "Error! Image is not uploaded.",
"result" => "error"
));
}
mysqli_close($connection);
} else {
echo json_encode(array(
"response" => "Error! No database connection!",
"result" => "error"
));
}
}
} else {
echo json_encode(array(
"response" => "Error! Please insert data!",
"result" => "error"
));
}
?>
看看 php 和 $_FILES
数组move_uploaded_file()
函数。
这个网站上有很多示例代码。
如果您想在后端添加分段上传,您应该进行下一步更改:
<?php
//header('Content-Type : bitmap; charset=utf-8');
//header('Content-Type: application/json');
if (isset($_POST["encoded_string"])) {
//encoded_string -> base64 string sent from mobile phone
if (!file_exists('images')) {
mkdir('images', 0777, true);
}
$connection = mysqli_connect('localhost', 'root', '', 'test');
if (!$connection) {
echo json_encode(array(
"response" => "Error! No database connection!",
"result" => "error"
));
die;
}
$responses = array();
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$image_name = $_FILES["pictures"]["name"][$key];
$path = 'images/' . $image_name;
if (move_uploaded_file($tmp_name, path)) {
$query = "INSERT INTO photos(name,path) values('$image_name','$path');";
$result = mysqli_query($connection, $query);
if ($result) {
$responses[] = array(
"response" => "Success! Image is succefully uploaded!.",
"result" => "success"
);
} else {
$responses[] = array(
"response" => "Error! Image is not uploaded.",
"result" => "error"
);
}
}
} else {
$responses[] = array(
"response" => "Error! Please insert data!",
"result" => "error"
);
}
}
mysqli_close($connection);
echo json_encode(array(
'responses' => $responses
));
}
另外,让您使用多部分格式的 post 请求(它应该有标题内容类型:多部分/表单数据和正确格式的 bi - https://ru.wikipedia.org/wiki/Multipart/form-data)。希望对您有所帮助。