第三百一十九节,Django框架,文件上传
第三百一十九节,Django框架,文件上传
1、自定义上传【推荐】
请求对象.FILES.get()获取上传文件的对象
上传对象.name获取上传文件名称
上传对象.chunks()获取上传数据包,字节码类型
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="/static/css/tou.css"> </head> <body> <form action="/bugarticles/" enctype="multipart/form-data" method="post"> <input type="file" name="shch"/> <input type="submit" value="上传"/> </form> </body> </html>
逻辑处理
from django.shortcuts import render,redirect import 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 models class 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