Save content of zip file in django

Viewed 24

Good Day,

I would like to save the content of the zip file. My code works, but they save only the filename and not the content or actual files neither in the database nor the project.

I need to save in the database the content of each file. Can someone please help me to fix my error? My code looks like this:

uploaded_file, = request.FILES.getlist('document[]')
                with zipfile.ZipFile(uploaded_file.file, mode="r") as archive:
                    for zippedFileName in archive.namelist():
                            newZipFile = UploadedFile(document= zippedFileName)
                            newZipFile.user= request.user
                            files = newZipFile.save()
                            success=True
                return render(request, 'uploader/index.html', {'files': [uploaded_file]})
2 Answers

For people looking on how to save the content of a zip file, this solution works for me

IMAGE_FILE_TYPES = ['png', 'jpg', 'jpeg']

def PostCreate(request):
form = PostForm()
if request.method == 'POST':
    form = PostForm(request.POST, request.FILES)
    if form.is_valid():
        user_pr = form.save(commit=False)
        user_pr.album_image = request.FILES['album_image']
        with zipfile.ZipFile(user_pr.album_image, mode="r") as archive:
            for fileName in archive.namelist():
                file_type = fileName.split('.')[-1]
                file_type = file_type.lower()
                if file_type not in IMAGE_FILE_TYPES:
                    print("ERROR!!!")
                else:
                    file= archive.extract(fileName, settings.MEDIA_ROOT + 'UnzippedFiles')                        
                    rbe = Post.objects.create(album_image=file)
                    rbe.save()
                    print("SUCESS!!!")
        return render(request, 'photos/post.html', {'user_pr': user_pr})

context = {"form": form,}
return render(request, 'photos/post_form.html', context)
Related