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)
相关推荐
炸薯条!27 分钟前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
tryCbest1 小时前
Python 爬虫从入门到实战(二):进阶篇——反爬对抗、并发与动态页面
开发语言·爬虫·python
VIP_CQCRE1 小时前
GPT Image 2.6 动态表情交付别只发预览:GIF 文件校验、哈希清单与下载排错
图像处理·人工智能·python·gif
2601_967987371 小时前
使用 NumPy 和 Python 实现梯度下降
python·机器学习·线性回归·numpy·梯度下降
BD_Marathon2 小时前
Jupyter魔法命令
ide·python·jupyter
词却2 小时前
Python 正则表达式实战:使用 re 模块提取符合条件的字符串
python·正则表达式
汤姆宝库3 小时前
视觉语言模型的实现:LLaVA式投影与指令微调
python·深度学习·语言模型
2601_9679791213 小时前
初学者必知的Python中优雅的用法
python·枚举·初学者·优雅用法·字典解析
AI创界者15 小时前
Python 进阶实战(五十八章):配置热更新、优雅停机排空与高并发压测方案
人工智能·python·aigc
2601_9679873718 小时前
python网络工程师自动化运维课程
python·正则表达式·网络工程师·模块·自动化运维