django文件上传文件类型限制方法

django文件上传文件类型限制方法

在处理上传views中:

def add(request):
if request.POST:
file = request.FILES.get(‘uploadfile’, None)
if file:
name = request.POST[‘name’]
str_time = time.strftime(‘%Y-%m-%d-%H%M%S’, time.localtime(time.time()))
fname = file.name;
fname = str_time + fname[fname.rfind(‘.’):]
file_name_suffix = os.path.splitext(file.name)[1].lower()
if not file_name_suffix in settings.ALLOW_FILE_TYPES:    #在settings中添加ALLOW_FILE_TYPES = (‘.doc’,’.pdf’,’.txt’,’.jpg’, ‘.jpeg’, ‘.gif’, ‘.bmp’, ‘.png’, ‘.tiff’)
return HttpResponse(simplejson.dumps({“statusCode”:300, “navTabId”:request.POST.get(‘navTabId’, ‘photoindex’), “callbackType”:request.POST.get(‘callbackType’, ‘closeCurrent’), “message”:u’上传文件类型不支持’}), mimetype=’application/json’)
of = open(settings.FILE_UPLOAD_TEMP_DIR + fname, ‘wb+’)
for chunk in file.chunks():
of.write(chunk)
of.close()
photo = Photo(name=name, images_path=fname)
photo.save()
return HttpResponse(simplejson.dumps({“statusCode”:200, “navTabId”:request.POST.get(‘navTabId’, ‘photoindex’), “callbackType”:request.POST.get(‘callbackType’, ‘closeCurrent’), “message”:u’添加成功’}), mimetype=’application/json’)
#return HttpResponseRedirect(reverse(“index”))
else:
return render(request, ‘photo/add.html’)

发表评论

电子邮件地址不会被公开。 必填项已用*标注