文章目录
- 项目初始化配置
- 具体文件上传下载代码的实现
- 数据库模型类建立
- 运行测试
项目初始化配置
1.使用pycharm编辑器新建一个django项目
2.Terminal终端下载需要的依赖包
# 和数据库建立连接的依赖包
pip install mysqlclient
# 解决跨域问题的依赖包
pip install django-cors-headers
3.Terminal注册一个需要的app
python manage.py startapp users
4.修改settings.py里面的部分配置信息
5.主路由和子路由的修改配置
5.1主路由(sky指的是你python manage.py startapp "你的名称,根据自己的来)
5.2子路由:在你的sky文件下面创建urls.py,并填写以下内容
6.数据库迁移,终端输入以下语句
python manage.py makemigrations
python manage.py migrate
具体文件上传下载代码的实现
数据库模型类建立
1.在sky/models.py书写以下代码
from django.db import models
# Create your models here.
class UploadedFile(models.Model):
file = models.FileField(upload_to='uploads/')
uploaded_at = models.DateTimeField(auto_now_add=True)
mime_type = models.CharField(max_length=100, default="") # 添加mime_type字段
def __str__(self):
return self.file.name
2.再次执行迁移文件,将数据库表迁移
python manage.py makemigrations
python manage.py migrate
3.在sky/views下书写以下代码(上传/下载/时间获取接口)
import os
from django.http import JsonResponse, HttpResponse
from .models import UploadedFile
# 定义一个字典,用于将文件扩展名映射到 MIME 类型
MIME_TYPES = {
'.txt': 'text/plain; charset=utf-8',
'.pdf': 'application/pdf',
'.xls': 'application/vnd.ms-excel',
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.kmz': 'application/vnd.google-earth.kmz',
# 添加其他文件类型的映射
}
# 文件上传接口
def upload_file(request):
if request.method == 'POST' and request.FILES.get('file'):
uploaded_file = request.FILES['file']
# 获取文件扩展名,了解是上传的什么类型的文件
file_extension = os.path.splitext(uploaded_file.name)[1].lower()
# 获取文件类型的 MIME 类型(application/octet-stream标识默认返回类型)
mime_type = MIME_TYPES.get(file_extension, 'application/octet-stream')
# 保存文件时同时保存文件类型信息
uploaded_file_object = UploadedFile.objects.create(
file=uploaded_file,
mime_type=mime_type # 保存文件类型信息
)
# 其他处理逻辑...
return JsonResponse({'success': True, 'file_id': uploaded_file_object.id})
else:
return JsonResponse({'error': 'File not provided'})
# 文件下载接口
def download_file(request, file_id):
try:
upload_file = UploadedFile.objects.get(id=file_id)
file_path = upload_file.file.path
# 获取文件类型信息
mime_type = upload_file.mime_type
with open(file_path, 'rb') as file:
response = HttpResponse(file.read(), content_type=mime_type)
response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(file_path)
return response
except UploadedFile.DoesNotExist:
return JsonResponse({'error': 'File not found'})
# 删除文件接口
def delete_file(request, file_id):
if request.method == 'DELETE':
try:
uploaded_file = UploadedFile.objects.get(id=file_id)
file_path = uploaded_file.file.path
# 从数据库中删除文件记录
uploaded_file.delete()
# 删除文件
if os.path.exists(file_path):
os.remove(file_path)
return JsonResponse({'success': True})
except UploadedFile.DoesNotExist:
return JsonResponse({'error': 'File not found'})
else:
return JsonResponse({'error': 'Method not allowed'}, status=405)
# 获取文件上传时间接口
def get_upload_time(request, file_id):
try:
uploaded_file = UploadedFile.objects.get(id=file_id)
upload_time = uploaded_file.uploaded_at.strftime("%Y-%m-%d %H:%M:%S")
return JsonResponse({'upload_time': upload_time})
except UploadedFile.DoesNotExist:
return JsonResponse({'error': 'File not found'})
4.sky/urls路由配置信息
# 应用程序目录下的 urls.py
from django.urls import path
from . import views
urlpatterns = [
path('uploadfile/', views.upload_file),
path('downloadfile/<int:file_id>/', views.download_file),
path('deletefile/<int:file_id>/', views.delete_file),
path('getUpdateTime/<int:file_id>/', views.get_upload_time)
]
运行测试
1.运行项目
Terminal执行
python manage.py runserver
2.使用postman测试上传功能和下载功能
注意红框部分要和我一致
上传:
下载:
测试成功。上传下载功能实现