django中文件的上传问题
发布日期:2021-05-14 15:20:33 浏览次数:9 分类:精选文章

本文共 3037 字,大约阅读时间需要 10 分钟。

Django 文件上传解决方案

在开始解决这个问题之前,首先要理解Django如何处理文件上传请求。这涉及到客户端和服务器端的协调工作,包括请求的发送、文件的接收和存储。

客户端(client.py)

如果需要将文件上传到服务器,主要步骤是:

  • 配置请求头: 确保在发送文件时,请求头包含正确的内容类型,如enctype="multipart/form-data",这会告诉服务器这是一个文件上传请求。
  • 构建文件信息: 包含文件名、文件内容和文件类型的元数据。
  • 发送HTTP请求: 使用:requests.post()方法将文件内容发送到指定的URL。
  • 这里是一个示例:

    import requests
    import os
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    if __name__ == "__main__":
    url = "http://127.0.0.1:8001/gen_model/predict/"
    while True:
    input_content = input('输入图片路径(按回车退出):').strip()
    if not input_content:
    input_content = 'test.png'
    if input_content == 'q':
    break
    file_path = os.path.join(BASE_DIR, 'media', input_content)
    if not os.path.exists(file_path):
    print('图片文件不存在!请检查路径是否正确。')
    continue
    file_name = os.path.basename(file_path)
    file_data = open(file_path, 'rb')
    # 提取文件扩展名
    ext = os.path.splitext(file_path)[1]
    headers = {'_enetcode': 'multipart/form-data'}
    files = {'img': (file_name, file_data, 'image/' + ext)}
    response = requests.post(url, headers=headers, files=files)
    print(f"上传状态:{response.status_code}")
    print(f"预测结果:{response.text}")

    Django 服务器端

    接下来配置Django服务器端接收文件的逻辑:

  • 创建API视图: 使用APIView来处理HTTP请求。
  • 验证和处理文件:post方法中,获取文件,并将其存储到媒体文件夹。
  • 返回结果: 返回处理结果,例如文件路径。
  • from django.views.decorators.csrf import csrf_exempt
    from django.views.generic.base import View
    from django.conf import settings
    from django.shortcuts import redirect
    class PredictView(View):
    @csrf_exempt
    def post(self, request):
    file = request.FILES.get('img', None)
    if not file:
    return redirect('/')
    file_path = os.path.join(settings.MEDIA_ROOT, '上传的图片')
    file_name = os.path.basename(file.name)
    file_ext = os.path.splitext(file.name)[1]
    file_path = os.path.join(file_path, file_name)
    # 创建目标路径
    if not os.path.exists(os.path.dirname(file_path)):
    os.makedirs(os.path.dirname(file_path))
    # 保存文件
    with open(file_path, 'wb') as fp:
    for chunk in file.chunks():
    fp.write(chunk)
    return redirect(f'/image/{file_path.split(os.path.sep)[-1:]}')

    前端配置(HTML)

    在页面中添加文件上传的表单,确保使用正确的enctype

    图片上传

    图片上传工具

    媒体文件配置

    确保Django的媒体文件配置:

  • 在 settings.py 中:

    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    MEDIA_URL = '/media/'
  • 在 URLs.py 中,确保有:

     
  • from django.urls import include, path urlpatterns = [ path('gen_model/predict/', include('predict.urls')), ]

    3. **创建 include 模块(如果没有):**
    ```python
    from django.urls import re_path
    from . import PredictView
    urlpatterns = [
    re_path(r'^gen_model/predict/', PredictView.as_view()),
    ]

    注意事项

    • 文件名处理: 确保文件名不包含有问题的字符,防止存储失败。
    • 权限管理: 确保媒体文件夹有适当的权限权限,否则会导致权限错误。
    • 缓存管理: 因为文件是在资源有限的云端存储,如果删除旧文件,需要清理媒体目录。
    • 错误处理: 在接收文件时,增加异常处理,确保正确日志和提示。
    • 验证文件类型: 可以对文件的MIME类型进行检查,确保只接收允许类型的文件。

    通过以上步骤,Django文件上传应该能正常运行。你可以测试上传一个图片,看看是否能成功保存到服务器,并接收到预期的响应。

    上一篇:pytorch打印当前学习率
    下一篇:Django中request.data[‘key‘]与request.data.get(‘key‘)的区别

    发表评论

    最新留言

    感谢大佬
    [***.8.128.20]2025年04月14日 06时36分22秒