您好,登錄后才能下訂單哦!
很久沒更新博客了,最近在寫項目沒時間,做到文件上傳的適合,看了蟲師的博客覺得不錯,就順便記錄一下自己的操作過程:
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。