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)
