django上传文件

1、settings.py配置

复制代码
# 静态文件配置
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR /'static',
]

上传文件

复制代码
# 定义一个视图函数,该函数接收一个 request 参数
from django.shortcuts import render
# 必备引入
import json
from django.views.decorators.http import require_POST, require_http_methods
from django.http import JsonResponse
import time
# 其它引入
import os
import uuid

def home_view(request):
    # 使用 HttpResponse 包装要返回的字符串
    # return HttpResponse("欢迎使用许大得商城")
    context = {
        'message': '欢迎使用许大得商城!'
    }
    return render(request, 'myDjangoWb/index.html', context)

# 上传文件
@require_http_methods(["POST"])
def upload(request):
    data = {
        "code": "2000",
        "data": [],
        "message": "查询成功"
    }
    # 检查请求中是否包含文件
    if request.FILES.get('file'):
        uploaded_file = request.FILES['file']
        # 获取静态文件目录路径
        date = time.strftime("%Y%m%d", time.localtime())  # 当前日期
        static_dir = os.path.join(os.getcwd(), 'static', date)
        # 如果目录不存在,则创建
        if not os.path.exists(static_dir):
            os.makedirs(static_dir)
        # 获取文件扩展名
        file_ext = os.path.splitext(uploaded_file.name)[1]
        # 生成唯一的文件名
        unique_name = f'{uuid.uuid4().hex}{file_ext}'
        # 生成文件保存的完整路径
        file_path = os.path.join(static_dir, unique_name)
        print(file_path)
        try:
            # 保存文件
            with open(file_path, 'wb+') as destination:
                for chunk in uploaded_file.chunks():
                    destination.write(chunk)
            data['message'] = '文件上传成功'
            data['data'] = [f'/static/uploads/{unique_name}']
        except Exception as e:
            data['code'] = "2001"
            data['message'] = f'文件上传失败: {str(e)}'
    else:
        data['code'] = "2001"
        data['message'] = '未接收到文件'
    return JsonResponse(data)
相关推荐
u***32435 小时前
使用python进行PostgreSQL 数据库连接
数据库·python·postgresql
青瓷程序设计8 小时前
动物识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
tobebetter95278 小时前
How to manage python versions on windows
开发语言·windows·python
F_D_Z8 小时前
数据集相关类代码回顾理解 | sns.distplot\%matplotlib inline\sns.scatterplot
python·深度学习·matplotlib
daidaidaiyu9 小时前
一文入门 LangGraph 开发
python·ai
不知更鸟10 小时前
前端报错:快速解决Django接口404问题
前端·python·django
4***721310 小时前
【玩转全栈】----Django模板语法、请求与响应
数据库·python·django
c***421010 小时前
Django视图与URLs路由详解
数据库·django·sqlite
梁正雄10 小时前
1、python基础语法
开发语言·python
2***656311 小时前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite