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)
相关推荐
程序小武8 分钟前
python编辑器如何选择?
后端·python
一叶知秋121116 分钟前
UV管理python项目
python
AndrewHZ22 分钟前
【图像处理入门】2. Python中OpenCV与Matplotlib的图像操作指南
图像处理·python·opencv·计算机视觉·matplotlib·图像操作
golitter.1 小时前
langchain学习 01
python·学习·langchain
一叶知秋12111 小时前
LangChain Prompts模块
python
量化金策2 小时前
截面动量策略思路
python
心软且酷丶2 小时前
leetcode:7. 整数反转(python3解法,数学相关算法题)
python·算法·leetcode
逾非时3 小时前
python:selenium爬取网站信息
开发语言·python·selenium
天才测试猿3 小时前
Selenium操作指南(全)
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
不学无术の码农4 小时前
《Effective Python》第六章 推导式和生成器——避免在推导式中使用超过两个控制子表达式
开发语言·python