Django Bulk File Upload/Download
In Django, you can use the built-in file upload handling feature to batch upload and download files. Here is a simple example:
- Batch upload files:
from django.shortcuts import render
from django.core.files.storage import FileSystemStorage
def upload_files(request):
if request.method == 'POST' and request.FILES.getlist('files'):
for file in request.FILES.getlist('files'):
fs = FileSystemStorage()
fs.save(file.name, file)
return render(request, 'upload.html')
In the example above, we have defined a view function called upload_files to handle the bulk upload of files. In the POST request, we use request.FILES.getlist(‘files’) to retrieve all the uploaded files, and then save them one by one to the file system.
- Download files in bulk.
import os
from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage
def download_files(request):
files = os.listdir('path_to_files_directory')
response = HttpResponse(content_type='application/zip')
zip_file = FileSystemStorage().zip_folder('path_to_files_directory', files)
response['Content-Disposition'] = 'attachment; filename="files.zip"'
response['Content-Length'] = os.path.getsize(zip_file)
response.write(open(zip_file, 'rb').read())
return response
In the example above, we have defined a view function download_files to handle the batch downloading of files. Initially, we retrieve a list of all files in the folder, then we bundle these files into a zip file and return it as a response for the user to download.
It is important to note that the above examples are just demonstrating the basic methods for bulk uploading and downloading files, further modifications and optimizations based on specific requirements may be necessary in actual applications.