欢迎访问宙启技术站
智能推送

Python中使用FileResponse()函数实现文件的上传和下载

发布时间:2023-12-24 16:37:43

在Python中,我们可以使用FileResponse()函数实现文件的上传和下载。该函数位于django.http模块中,用于构造一个包含文件内容的HTTP响应。

下面是一个简单的使用例子,假设我们有一个名为upload.html的网页文件,用户可以在该页面上选择一个文件并上传到服务器上:

<!DOCTYPE html>
<html>
  <head>
    <title>文件上传</title>
  </head>
  <body>
    <h1>文件上传</h1>
    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      <input type="file" name="file" accept="image/*">
      <input type="submit" value="上传">
    </form>
  </body>
</html>

然后,在服务器端的视图函数中,我们可以获取用户上传的文件并保存到指定的位置:

from django.shortcuts import render
from django.http import FileResponse

def upload_file(request):
    if request.method == 'POST' and request.FILES['file']:
        uploaded_file = request.FILES['file']
        with open('uploaded_files/' + uploaded_file.name, 'wb') as destination:
            for chunk in uploaded_file.chunks():
                destination.write(chunk)
        return render(request, 'success.html')
    return render(request, 'upload.html')

在上面的代码中,我们首先检查请求方法是否为POST,并且是否有名为'file'的文件被上传。如果有,我们使用open()函数打开一个文件来保存上传的文件内容。然后,我们通过迭代上传的文件的chunks()来逐块写入目标文件。

如果文件上传成功,我们可以返回一个成功页面。否则,我们将返回上传页面,继续等待用户上传文件。

接下来,我们可以实现一个文件下载的示例。假设我们有一个名为download.html的页面,用户可以在该页面上选择要下载的文件:

<!DOCTYPE html>
<html>
  <head>
    <title>文件下载</title>
  </head>
  <body>
    <h1>文件下载</h1>
    <form method="post">
      {% csrf_token %}
      <select name="file">
        <option value="file1.txt">file1.txt</option>
        <option value="file2.txt">file2.txt</option>
      </select>
      <input type="submit" value="下载">
    </form>
  </body>
</html>

然后,在服务器端的视图函数中,我们可以根据用户选择的文件名来构造FileResponse对象,并将其发送给用户进行下载:

from django.shortcuts import render
from django.http import FileResponse

def download_file(request):
    if request.method == 'POST' and request.POST['file']:
        file_name = request.POST['file']
        file_path = 'download_files/' + file_name
        response = FileResponse(open(file_path, 'rb'))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename=' + file_name
        return response
    return render(request, 'download.html')

在上面的代码中,我们首先获取用户选择的文件名,并构造文件的完整路径。然后,我们使用open()函数打开该文件,并将其作为参数传递给FileResponse函数来创建一个文件响应对象。接下来,我们可以设置响应头信息,如Content-TypeContent-Disposition,以指定下载文件的类型和名称。

最后,我们将响应对象返回给客户端,以触发下载操作。如果用户未选择文件,则返回下载页面。

以上是使用FileResponse()函数实现文件的上传和下载的简单示例。当然,在实际情况中,我们还需要进行错误处理、身份验证和安全控制等。希望这个例子能帮助你理解如何在Python中使用FileResponse()函数来处理文件上传和下载。