-- 上传图片
-- 注意点:
1.在输入框标签input添加type='file'属性,且name=''表示键;
2.FILES在请求POST,且<form>表单带有enctype="multipart/form-data"的
属性时才可以包含数据;否则FILES为一个空的类似于字典的对象;
-- 将属性定义为models.ImageField类型;(模型类)
pic = models.ImageField(upload_to='cars/')
-- 如果属性类型为ImageField需要安装包Pillow
pip install Pillow==3.4.1
-- 图片存储路径
-- /static/media/cars/图片文件
-- setting.py文件,增加media_root项;
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
-- 实例
-- views.py
# def uploadHandle(request): # # 获取图片的对象 # pic1 = request.FILES['pic1'] # # 拼接图片所在完整路径 # picName = os.path.join(settings.MEDIA_ROOT, pic1.name) # # IO操作,chunks()一点点的读取; # with open(picName, 'w') as pic: # for c in pic1.chunks(): # pic.write(c) # # 返回图片路径 # return HttpResponse('<img src="/static/media/%s/">'%pic1.name)
-- urls.py
# url(r'^uploadPic/$', views.uploadPic), # url(r'^uploadHandle/$', views.uploadHandle),
-- uploadPic.html
<form action="/uploadHandle" method="post" # 表单传递到/uploadHandle路径下,同时定义视图函数uploadHandle读取返回图片; enctype="multipart/form-data"> <input type="file" name="pic1"> <br> <input type="submit" name="上传"> </form>