第三百一十九节,Django框架,文件上传
1、自定义上传【推荐】
请求对象.FILES.get()获取上传文件的对象
上传对象.name获取上传文件名称上传对象.chunks()获取上传数据包,字节码类型html
Title
逻辑处理
from django.shortcuts import render,redirectimport os#逻辑处理模块def special(request): if request.method == "POST": obj = request.FILES.get('shch') #获取上传文件对象 f = open(os.path.join("app1", obj.name), 'wb') #以读写字节模式打开,存在覆盖没有创建 for chunk in obj.chunks(): #循环文件数据块 f.write(chunk) #写入文件 f.close() #关闭打开文件 return render(request, 'app1/index.html',locals())
内置方式
表单验证模块
class FileForm(forms.Form): ExcelFile = forms.FileField()
数据库操作Models模块
from django.db import modelsclass UploadFile(models.Model): userid = models.CharField(max_length = 30) file = models.FileField(upload_to = './upload/') date = models.DateTimeField(auto_now_add=True)
逻辑处理模块
def UploadFile(request): uf = AssetForm.FileForm(request.POST,request.FILES) if uf.is_valid(): upload = models.UploadFile() upload.userid = 1 upload.file = uf.cleaned_data['ExcelFile'] upload.save() print upload.file