Apr 30, 2023
0
Level 1
aws-sdk-php deleting object problem
Hello all, Am trying to delete the image on minio with aws-sdk-php. But it's returning 405. With the upload function, I didn't have any problem.
This is my code:
public function deleteImage(Request $request)
{
$validator = Validator::make($request->all(), [
'imageUrl' => 'required|string'
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()], 400);
}
$validated = $validator->validated();
$urlPath = parse_url($validated['imageUrl'], PHP_URL_PATH);
$pathParts = explode('/', $urlPath);
// images/a6371b07-16d6-455e-9afa-db1e211883e1-heh.jpg ( location / image)
$imageLocationAndName = implode('/', array_slice($pathParts, -2));
// bucketName/images/a6371b07-16d6-455e-9afa-db1e211883e1-heh.jpg ( bucket name / location / image)
$key = ltrim(parse_url($validated['imageUrl'], PHP_URL_PATH), '/');
// Set up the S3 client
$s3Client = new S3Client([
'version' => 'latest',
'region' => env('AWS_DEFAULT_REGION'),
'endpoint' => env('AWS_ENDPOINT'), // minio endpoint
'credentials' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
],
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT'), // true
]);
try {
// Check if the file exists
if (!$s3Client->doesObjectExist(env('AWS_BUCKET_NAME'), $imageLocationAndName)) {
return response()->json([
'message' => 'File not found.',
], 404);
}
// Delete the S3 object
$result = $s3Client->deleteObject([
'Bucket' => env('AWS_BUCKET_NAME'),
'Key' => $imageLocationAndName,
]);
// Delete the file from the database
File::where('url', $validated['imageUrl'])->delete();
return response()->json([
'message' => 'Image was successfully deleted.',
], 200);
} catch (\Exception $e) {
return response()->json([
'message' => 'Failed to delete the image.', $e->getMessage(),
], 500, [], JSON_UNESCAPED_SLASHES);
}
}
Its returns this error
{
"message": "Failed to delete the image.",
"0": "Error executing \"DeleteObject\" on \"https://myEndPoint/MyBucket/images/a6371b07-16d6-455e-9afa-db1e211883e1-heh.jpg\"; AWS HTTP error: Client error: `DELETE https://myEndPoint/MyBucket/images/a6371b07-16d6-455e-9afa-db1e211883e1-heh.jpg` resulted in a `405 Not Allowed` response:\n<html>\r\n<head><title>405 Not Allowed</title></head>\r\n<body>\r\n<center><h1>405 Not Allowed</h1></center>\r\n<hr><center>ngin (truncated...)\n Unable to parse error information from response - Error parsing XML: String could not be parsed as XML"
}
I was thinking that it was a permissions problem, but with minio client, I entered the server and deleted the image. so I don't think that it's a permission problem. What am doing wrong? Can someone please help?
Please or to participate in this conversation.