1. 程式人生 > 其它 >DRF 上傳檔案介面

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 測試檔案上傳介面