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]})
CodePudding user response:
You have to save your zipfile on your filesystemstorage : https://docs.djangoproject.com/fr/4.1/ref/files/storage/
Or you can use a BinaryField in your models and try to save your zipfile as encoded binary : https://docs.djangoproject.com/fr/4.1/ref/models/fields/#binaryfield
THe better way is clearly the usage of a FS i think
CodePudding user response:
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)