Reputation: 1155
I have used this answer to delete a file from s3 bucket
The task I need to perform is when I'm uploading a new image I need to delete the previous one. So after upload, I'm calling deletion for the previous image. The deletion method gives me success but the file is still there in a bucket. So now, I can see both of the files; the previous one and the new one too. Am I missing something?
Here's my code of upload & delete
func uploadfile(image: UIImage, s3Key: String, bucketName: String, completionHandlerWithImageURL: @escaping(_ imageurl: String) -> ())
{
let transfer_utility = S3TransferUtilityConfig().config()
let expression = S3Expression().config()
var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
completionHandler = { (task, error) -> Void in
debugPrint("Upload Completed")
}
let bucketName = bucketName
guard let data = image.pngData() else{
return
}
transfer_utility?.uploadData(data as Data, bucket: bucketName, key: s3Key, contentType: "image/png", expression: expression,
completionHandler: completionHandler).continueWith
{
(task) -> AnyObject? in
if let error = task.error {
print(error.localizedDescription)
completionHandlerWithImageURL("")
}
if let _ = task.result {
debugPrint("Uploaded image successfully")
if task.result != nil {
let url = AWSS3.default().configuration.endpoint.url
let publicURL = url?.appendingPathComponent(bucketName).appendingPathComponent(s3Key)
if let absoluteString = publicURL?.absoluteString {
debugPrint("Image Url :\(absoluteString)")
completionHandlerWithImageURL(absoluteString)
}
} else {
debugPrint("Image URL not generated")
completionHandlerWithImageURL("")
}
}
return nil
}
}
func deleteExistingFile(s3Key: String, bucketName: String) {
let s3 = AWSS3.default()
guard let deleteObjectRequest = AWSS3DeleteObjectRequest() else { return }
deleteObjectRequest.bucket = bucketName
deleteObjectRequest.key = "/images/\(s3Key.components(separatedBy: "/").last ?? "")"
s3.deleteObject(deleteObjectRequest).continueWith { (task:AWSTask) -> AnyObject? in
if let error = task.error {
print("Error deleting file on s3 bucket: \(error)")
return nil
} else {
print("s3 file Deleted successfully. \(bucketName) \(s3Key)")
return nil
}
}
}
This is how I have called both the methods.
S3Manager.shared.uploadfile(image: image, s3Key: self.img_key, bucketName: (company_profile["dot"] as? String ?? ""))
{ (imgUrl) in
if imgUrl != ""
{
S3Manager.shared.deleteExistingFile(s3Key: self.profileUrl, bucketName: (company_profile["dot"] as? String ?? ""))
...
...
}
}
Uploaded image path: https://s3.us-east-1.amazonaws.com/bucketNumber/images/img.png
I have tried deleteObjectRequest.key with the full path and only the folder / image path and in both the cases, method gives success but file is still there in a bucket.
deleteObjectRequest.key: https://bucketName.s3.amazonaws.com/images/old_img.png
deleteObjectRequest.key: /images/old_img.png
Upvotes: 0
Views: 229