DRF 上传文件接口

前言

django-rest-framework 开发文件上传接口

新建模型

models.py 创建模型

from django.db import models



class UpFile(models.Model):
    file = models.FileField(blank=True, null=False)
    title = models.CharField(max_length=30)
    timestamp = models.DateTimeField(auto_now_add=True)

创建完成后同步数据库

python manage.py makemigrations
python manage.py migrate

序列化和视图

from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework import serializers
from .models import UpFile
from rest_framework import validators
from rest_framework import status
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/


class FileSerializer(serializers.ModelSerializer):
    """序列化"""
    timestamp = serializers.DateTimeField(format=‘%Y-%m-%d %H:%M:%S‘, required=False)

    class Meta():
        model = UpFile
        fields = (‘file‘, ‘title‘, ‘timestamp‘)


class UpFileAPIView(APIView):
    parser_classes = (MultiPartParser, FormParser)

    def post(self, request, *args, **kwargs):
        file_serializer = FileSerializer(data=request.data)
        if file_serializer.is_valid():
            file_serializer.save()
            return Response({
                                "code": 0,
                                "msg": "success!",
                                "data": file_serializer.data
                            },
                            status=status.HTTP_200_OK
                            )
        else:
            return Response({
                                "code": 400,
                                "msg": "bad request",
                                "data": file_serializer.errors
                            },
                            status=status.HTTP_400_BAD_REQUEST)

urls.py配置接口访问地址

from django.conf.urls import url
from apiapp import views


urlpatterns = [
    url(r‘^api/v1/upfile/$‘, views.UpFileAPIView.as_view()),
]

postman测试接口

postman 测试文件上传接口

DRF 上传文件接口

上一篇:JS 根据id实现局部打印


下一篇:理解 MVCC