很久没更新博客了,最近在写项目没时间,做到文件上传的适合,看了虫师的博客觉得不错,就顺便记录一下自己的操作过程:
models 配置:
class User(models.Model): headImg = models.FileField(upload_to = './upload/') def __unicode__(self): return self.headImg
#####建立一个headImg字段###数据上传到数据库做记录并且在当前项目目录下建立upload文件夹。
html 文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> </head> <body> <h2>register</h2> <form method="post" enctype="multipart/form-data" > `uf`.`as_p` <input type="submit" value="ok"/> </form> </body> </html>
view 视图文件:
class UserForm(forms.Form): headImg = forms.FileField() def disk(request): if request.method == "POST": uf = UserForm(request.POST,request.FILES) if uf.is_valid(): headImg = uf.cleaned_data['headImg'] user = User() user.headImg = headImg user.save() return HttpResponse('upload ok!') else: uf = UserForm() return render_to_response('disk.html',{'uf':uf})
####form方式实现表单显示,并且上传文件。
上传成功:
mysql查看文件:
mysql> select * from app_user; +----+-------------------------------+ | id | headImg | +----+-------------------------------+ | 1 | upload/out_W3xCNAW.txt | | 2 | upload/out_429apY0.txt | | 3 | upload/out.txt | | 4 | upload/out_FAvse7g.txt | | 5 | upload/新建文本文档.txt | | 6 | upload/out_0Cve1aD.txt | +----+-------------------------------+
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。