Home > Blockchain >  python unable to extract zip file uploaded to aws s3 bucket
python unable to extract zip file uploaded to aws s3 bucket

Time:11-15

medias = ['https://baby-staging-bucket.s3.us-east-2.amazonaws.com/asset/0002.jpg', 
        'https://baby-staging-bucket.s3.us-east-2.amazonaws.com/asset/2.png', 
        'https://baby-staging-bucket.s3.us-east-2.amazonaws.com/asset/02.png'
    ]
for i in medias:
    file_name = i.split("/")[-1]
    urllib.urlretrieve (i, "media/" file_name)

# writing files to a zipfile
local_os_path = f'media/{title}.zip'
with ZipFile(local_os_path, 'w') as zip:
    # writing each file one by one
    for file in medias:
        file_name = file.split("/")[-1]
        zip.write("media/" file_name)
        os.remove("media/" file_name)
    
    s3 = session.resource('s3')
    storage_path = f'asset/nfts/zip/{title}.zip'
    s3.meta.client.upload_file(Filename=local_os_path, Bucket=AWS_STORAGE_BUCKET_NAME, Key=storage_path)
    # os.remove(local_os_path)
    DesignerProduct.objects.filter(id=instance.id).update(
        zip_file_path=S3_BUCKET_URL   storage_path, 
    )

I am using this code to create zip file and saving to w3 bucket. Fitst i am downloading to localsystem then zipping all files and saving zip file to s3 bucket In my local system i am able to extract zip file but when i download from s3 bucket i am not able to extract it.

https://baby-staging-bucket.s3.us-east-2.amazonaws.com/asset/nfts/zip/ant.zip

This is my path of s3 where zip file uploaded . what can be the reason please take a look

CodePudding user response:

Move the upload after the with block.

You are uploading your zipfile before the archive is closed. See ZipFile.close():

Close the archive file. You must call close() before exiting your program or essential records will not be written.

close is automatically called by the with statement.

You open your local file after the program exits - which means after the zipfile is closed - so your local version is not corrupted.

  • Related