很久没更新博客了,最近在写项目没时间,做到文件上传的适合,看了虫师的博客觉得不错,就顺便记录一下自己的操作过程:
models 配置:
1
2
3
4
|
class User(models.Model):
headImg = models.FileField(upload_to = './upload/' )
def __unicode__( self ):
return self .headImg
|
#####建立一个headImg字段###数据上传到数据库做记录并且在当前项目目录下建立upload文件夹。
html 文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<?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>
<h1>register< / h1>
<form method = "post" enctype = "multipart/form-data" >
`uf`.`as_p`
< input type = "submit" value = "ok" / >
< / form>
< / body>
< / html>
|
view 视图文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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查看文件:
1
2
3
4
5
6
7
8
9
10
11
|
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 |
+ - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
|
本文转自 小罗ge11 51CTO博客,原文链接:http://blog.51cto.com/xiaoluoge/1689299,如需转载请自行联系原作者