使用Django上传下载文件

文件上传

准备工作

  1. 先下载Pillow,用作图片有效性的验证工作

pip install Pillow

  1. settings.py配置路径
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
  1. models
class Personal(models.Model):
    user_name = models.CharField(max_length=45, verbose_name='用户名')
    user_pwd = models.CharField(max_length=45, verbose_name='密码')
    header_img = models.ImageField(verbose_name='头像', upload_to="image/")

    class Meta:
        verbose_name = '用户信息表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.user_name
class VersionManager(models.Model):
    version_name = models.CharField(max_length=20, verbose_name='版本名')
    version_apk = models.FileField(verbose_name='APK', upload_to='apk/')

    class Meta:
        verbose_name = '版本表'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.version_name
  1. 序列化数据
from rest_framework import serializers
from upload.models import Personal,VersionManager
from django import forms

#forms.ModelForm:接收用户信息表单信息
class PersonalSerializers(forms.ModelForm):
    class Meta:
        model = Personal
        fields = ('__all__')

class VersionManagerSerializers(serializers.ModelSerializer):
    class Meta:
        model=VersionManager
        fields = ('__all__')
  1. views
# 上传图片(Django 表单提交,接口POST提交)
class UploadImage(APIView):
    def post(self, request):
        personal = PersonalSerializers(request.POST, request.FILES)
        if personal.is_valid():
            personal.save()
            return Response({'code': 200})
        else:
            return Response({'code': 100})

class VersionManagerList(APIView):
    def get(self, request):
        return Response({'code': 200, 'data': VersionManagerSerializers(VersionManager.objects.all(), many=True).data})

# 获取版本文件列表
class VersionManagerList(APIView):
    def get(self, request):
        return Response({'code': 200, 'data': VersionManagerSerializers(VersionManager.objects.all(), many=True).data})

  1. urls
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
                  path('admin/', admin.site.urls),
                  path('upload/', include('upload.urls')),
              ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

from django.urls import path
import upload.views as  sp

from django.conf import settings

urlpatterns = [
    path('upload', sp.UploadImage.as_view()),# 上传图片
    path('version', sp.VersionManagerList.as_view()), #获取版本列表
]

  1. 效果图
    使用Django上传下载文件_第1张图片
    使用Django上传下载文件_第2张图片
    使用Django上传下载文件_第3张图片

使用Django上传下载文件_第4张图片

你可能感兴趣的:(Python)