我上传图片没有任何问题:
Future<http.Response?> uploadIMG() async {
const List<String> allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
if (!allowedExtensions.contains(_tempFileExt)) {
throw ArgumentError(
'Invalid file extension. Only JPG, PNG, and GIF are allowed.');
}
http.Response? response;
List<int> imageBytes = _tempFile!.readAsBytesSync();
final imageSize = _tempFile!.readAsBytesSync().lengthInBytes;
String baseimage = base64Encode(imageBytes);
try {
response = await http.post(
Uri.parse("http://192.168.1.80/api/product/"),
headers: {
HttpHeaders.contentTypeHeader: "application/json",
},
body: jsonEncode(
<String, dynamic>{
"uploaded_image": baseimage,
"text": "text",
},
),
);
} catch (e) {
//
}
return response;
}
并用这段 php 代码接收它(图像上传和存储没有任何问题)
$json = file_get_contents("php://input");
$obj = json_decode($json);
$base64_string = $newProduct->uploaded_image;
$outputfile = x . DS . y . DS . z . DS . "product" . ".jpg";
$filehandler = fopen($outputfile, 'wb');
fwrite($filehandler, base64_decode($base64_string));
fclose($filehandler);
如果我尝试添加任何验证,它将停止工作并且文件不再保存。
if (isB64Encoded($base64_string)) { //proceed }
或
if (isImage($base64_string)) { //proceed }
功能...
public static function isB64Encoded($str) {
$decoded_str = base64_decode($str);
$Str1 = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $decoded_str);
if ($Str1!=$decoded_str || $Str1 == '') {
return false;
}
return true;
}
public static function isImage($base64ImageString) {
if(stristr($base64ImageString, 'image/')) {
return true;
}
return false;
}
如何检查它是否是图像及其大小?
谢谢