Django怎么處理文件上傳和下載

小億
99
2024-04-16 11:08:14
欄目: 編程語言

在Django中處理文件上傳和下載是比較簡單的。下面是一個(gè)簡單的示例來演示文件上傳和下載的處理:

  1. 文件上傳

首先,你需要?jiǎng)?chuàng)建一個(gè)能夠處理文件上傳的視圖函數(shù)。在這個(gè)視圖函數(shù)中,你可以通過request.FILES來獲取上傳的文件。然后,你可以將這個(gè)文件保存到服務(wù)器上的指定位置。

# views.py

from django.shortcuts import render
from django.conf import settings
import os

def upload_file(request):
    if request.method == 'POST':
        uploaded_file = request.FILES['file']
        file_path = os.path.join(settings.MEDIA_ROOT, uploaded_file.name)
        
        with open(file_path, 'wb+') as destination:
            for chunk in uploaded_file.chunks():
                destination.write(chunk)
        
        return render(request, 'upload_success.html')
    
    return render(request, 'upload_file.html')
  1. 文件下載

同樣地,你需要?jiǎng)?chuàng)建一個(gè)能夠處理文件下載的視圖函數(shù)。在這個(gè)視圖函數(shù)中,你可以通過HttpResponse將文件發(fā)送給用戶下載。

# views.py

from django.http import HttpResponse
from django.conf import settings
import os

def download_file(request):
    file_path = os.path.join(settings.MEDIA_ROOT, 'example.txt')
    
    with open(file_path, 'rb') as file:
        response = HttpResponse(file, content_type='application/octet-stream')
        response['Content-Disposition'] = 'attachment; filename="example.txt"'
        
        return response
  1. 配置URL

最后,你需要將這些視圖函數(shù)和URL進(jìn)行關(guān)聯(lián)。

# urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('upload/', views.upload_file, name='upload_file'),
    path('download/', views.download_file, name='download_file'),
]

通過以上步驟,你就可以在Django中實(shí)現(xiàn)文件上傳和下載的功能了。當(dāng)用戶訪問/upload/頁面上傳文件后,文件將會(huì)被保存到服務(wù)器上的指定位置。而當(dāng)用戶訪問/download/頁面時(shí),可以下載指定的文件。

0