django

Django怎么处理文件上传和下载

小亿
84
2024-04-16 11:08:14
栏目: 编程语言

在Django中处理文件上传和下载是比较简单的。下面是一个简单的示例来演示文件上传和下载的处理:

  1. 文件上传

首先,你需要创建一个能够处理文件上传的视图函数。在这个视图函数中,你可以通过request.FILES来获取上传的文件。然后,你可以将这个文件保存到服务器上的指定位置。

# 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. 文件下载

同样地,你需要创建一个能够处理文件下载的视图函数。在这个视图函数中,你可以通过HttpResponse将文件发送给用户下载。

# 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

最后,你需要将这些视图函数和URL进行关联。

# 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中实现文件上传和下载的功能了。当用户访问/upload/页面上传文件后,文件将会被保存到服务器上的指定位置。而当用户访问/download/页面时,可以下载指定的文件。

0
看了该问题的人还看了