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)
相关推荐
ZhengEnCi几秒前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 分钟前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L18 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅18 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅18 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L18 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅18 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L19 小时前
python的类&继承
python
Warson_L19 小时前
类型标注/type annotation
python