溫馨提示×

django怎么批量上傳下載文件

小億
272
2024-03-01 14:40:12
欄目: 編程語言

在Django中,可以使用Django的內置文件上傳處理功能來批量上傳和下載文件。以下是一個簡單的示例:

  1. 批量上傳文件:
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')

在上面的示例中,我們定義了一個視圖函數upload_files來處理文件的批量上傳。在POST請求中,我們使用request.FILES.getlist('files')獲取到所有上傳的文件列表,然后逐個保存到文件系統中。

  1. 批量下載文件:
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

在上面的示例中,我們定義了一個視圖函數download_files來處理文件的批量下載。首先,我們獲取文件夾中的所有文件列表,然后將這些文件打包成一個zip文件,并將其作為響應返回給用戶進行下載。

需要注意的是,以上示例僅為演示批量上傳和下載文件的基本方法,實際應用中還需要根據具體需求進行適當的修改和優化。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女