html file upload 上传图片
第一步: 这是一个上传图片的按钮
<form class="form-horizontal" method="post" action="{% url 'create_article' %}" enctype="multipart/form-data"> {% csrf_token %}
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">图片</label>
<div class="col-sm-10">
<input type="file" name="head_img">
</div>
</div>
</form>
上面这个按钮的将会把你选择本地的图片发送到 create_article 这个url条目中处理。
第二步:create_article这个url条目将交给下面views.py的内容处理
def create_article(request):
if request.method == "GET" :
return render(request,'create_aritcle.html')
elif request.method == "POST" :
print request.POST
print '----------'
print request.FILES ##查看上传图片的路径
bbs_generater = utils.ArticleGen(request)
res = bbs_generater.create()
html_ele ="""
Your article <<a href="/article/%s/"> %s</a>> has been created successfully !!!,
""" %(res.id, res.title)
return HttpResponse(html_ele)
第三步:上面的utils 模版内容如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'gaogd'
import os
import models
from s10day12bbs import settings
class ArticleGen(object):
def __init__(self,request):
self.requset = request
def parse_data(self):
form_data = {
'title' : self.requset.POST.get('title'),
'content' : self.requset.POST.get('content'),
'summary' : self.requset.POST.get('summary'),
'author_id' : self.requset.user.userprofile.id,
'head_img': '',
'category_id' : 1 ##这里应该是用户选择的才对
}
return form_data
def create(self):
self.data = self.parse_data()
bbs_obj = models.Article(**self.data)
bbs_obj.save()
filename = handle_upload_file(self.requset,self.requset.FILES['head_img']) #获取图片路径并保存到数据库
bbs_obj.head_img = filename
bbs_obj.save()
return bbs_obj
def update(self):
pass
def handle_upload_file(request, file_obj):
upload_dir = '%s/%s' % (settings.BASE_DIR, settings.FileUploadDir)
if not os.path.isdir(upload_dir):
os.mkdir(upload_dir)
print '---->', dir(file_obj)
with open('%s/%s' % (upload_dir, file_obj.name), 'wb') as destination:
for chunk in file_obj.chunks():
destination.write(chunk)
return file_obj.name
第二步:查看上传图片的路径
requset.FILES['head_img']
request.FILES ##查看上传图片的路径
第三步: 获取图片路径并保存到数据库。
##这个是图片处理的重点
def handle_upload_file(request, file_obj):
upload_dir = '%s/%s' % (settings.BASE_DIR, settings.FileUploadDir)
if not os.path.isdir(upload_dir):
os.mkdir(upload_dir)
print '---->', dir(file_obj)
with open('%s/%s' % (upload_dir, file_obj.name), 'wb') as destination:
for chunk in file_obj.chunks():
destination.write(chunk)
return file_obj.name
转载于:https://blog.51cto.com/lvnian/1858761