django上传图片和文件并保存在数据库

坏境:

PyCharm2016.2
Python2.7
Django1.9.4
上传路径:./up_load/
参考:http://python.usyiyi.cn/django/topics/http/file-uploads.html
http://www.cnblogs.com/linjiqin/p/3731751.html
http://www.cnblogs.com/fnng/p/3740274.html

上传文件(推荐)

代码:
数据库model设计:

1
2
3
4
from django.db import models
class UploadFile(models.Model):
title = models.CharField(max_length=50)
file_path = models.FileField(upload_to='./up_load/')

新增forms.py

1
2
3
4
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file_path = forms.FileField()

views.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# _*_ coding:utf-8 _*_
from django.shortcuts import render,render_to_response,HttpResponse
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from .models import UploadFile
from .forms import UploadFileForm
@csrf_exempt
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
print form
if form.is_valid():
# 获取表单信息
title = form.cleaned_data['title']
file_path = form.cleaned_data['file_path']
# 写入数据库
uploadfile = UploadFile()
uploadfile.title = title
uploadfile.file_path = file_path
uploadfile.save()
return HttpResponse('上传 成功!')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})

Upload.html

1
2
3
4
<form method="post" enctype="multipart/form-data">  {% csrf_token %}
{{ form.as_p }}
<input type="submit" value="上次文件">
</form>

上传图片

代码:
数据库models设计:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
headImg = models.FileField(upload_to='./up_load/')
def __unicode__(self):
return self.username
forms.py
from django import forms
class UseerForm(forms.Form):
username = forms.CharField()
headImg = forms.FileField()
views.py
# _*_ coding:utf-8 _*_
from django.shortcuts import render,render_to_response
from django.http import HttpResponse
from upload.forms import UseerForm
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from upload.models import User

@csrf_exempt 防止报csrf错误
def upload(request):
if request.method == 'POST':
uf = UseerForm(request.POST,request.FILES)
if uf.is_valid():
#获取表单信息
username = uf.cleaned_data['username']
headImg = uf.cleaned_data['headImg']
# 写入数据库
user = User()
user.username = username
user.headImg = headImg
user.save()
return HttpResponse('upload ok!')
else:
uf = UseerForm()
return render_to_response('upload.html',{'uf':uf})

Upload.html

1
2
3
4
<form method="post" enctype="multipart/form-data">  {% csrf_token %}
{{ uf.as_p }}
<input type="submit" value="ok">
</form>

网页效果


mysql数据库展示

不用form 方式,也可以使用以下形式

Index.html

1
2
3
4
<form action=" " enctype="multipart/form-data" method="post">{% csrf_token %}
<input type="file" name="file">
<input type="submit" value="upload">
</form>

Views.py

1
2
3
4
5
6
7
8
def index(request):
if request.method == "POST":
upload_dir = "static/imgs/upload"
file_obj = request.FILES['file']
with open('%s/%s' % (upload_dir, file_obj.name), 'wb') as destination:
for chunk in file_obj.chunks():
destination.write(chunk)
return render(request,'index.html')

此方法需要提前新增好static/imgs/upload文件夹

Comments

2017-03-03