django的上传与下载的优化

Python leaves 2年前 (2018-04-27) 263次浏览 0个评论

之前的教程中实现的比较简单,对于文件类型和大小的约束性不好。本文主要采用了forms的方式实现校验:
在views.py中实现简单的逻辑,并在urls做好相关的配置,对应的view如下:

#coding:utf-8
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .form import *
import os
@csrf_exempt
def upload(request):
    if request.method == "POST":
        uf = UploadFile(request.POST, request.FILES)
        if uf.is_valid():
            # uf.clean_file()
            if uf.error_response:
                return JsonResponse(uf.error_response)
            print('====uf is ok')
            # ‘file’为html的id=
            handle_upload_file(request.FILES['file'], str(request.FILES['file']))
            return HttpResponse('Successful')
    return render('upload.html')
@csrf_exempt
def handle_upload_file(file, filename):
    path = 'media/uploads/'
    if not os.path.exists(path):
        os.makedirs(path)
    with open(path+filename, 'wb+')as destination:
        for chunk in file.chunks():
            destination.write(chunk)

 
对应的upload.html实现:

...
<div class="row">
      <div class="col-md-8 col-md-offset-2">
          <form class="form-inline" role="form"  method="post" enctype="multipart/form-data" accept-charset="utf-8">
              <div class="form-group">
                  <input type="file" name="file">
              </div>
              <div class="form-group">
                  <input type="submit" value="上传文件">
              </div>
          </form>
      </div>
  </div>
...

form.py实现了文件类型的校验、大小的校验。另外,考虑到异常,此处自定了一些错误描述,具体如下:

from django import forms
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
class UploadFile(forms.Form):
    '''
    file 要与html中的id名称一致;
    '''
    error_response = {}
    file = forms.FileField(label='file')
    def clean_file(self):
        file = self.cleaned_data['file']
        # content_type = file.content_type.split('/')[0]
        #if content_type in settings.CONTENT_TYPES:
        # 此处配置文件存放在了项目的settings中
        if file.name.split('.')[-1] in settings.CONTENT_TYPES:
            if file.size > settings.MAX_UPLOAD_SIZE:
                raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(file.size)))
        else:
            self.error_response['msg'] = "not supported file type!"
            # raise forms.ValidationError(_('File type is not supported'))
        return file

setting.py中的配置:

CONTENT_TYPES = ['pdf', 'png', 'xls']
# 2.5MB - 2621440
# 5MB - 5242880
# 10MB - 10485760
# 20MB - 20971520
# 50MB - 5242880
# 100MB 104857600
# 250MB - 214958080
# 500MB - 429916160
MAX_UPLOAD_SIZE = 2*1024*1024

版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:django的上传与下载的优化
喜欢 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址