上传图片(很简单的操作)
准备:
urls.py
from django.conf.urls import url
import views
urlpatterns = [
url(r'^$',views.index),
url(r'^upload_pic/$',views.upload_pic), #不要忘记$不然因为贪婪这个和下面一个都会匹配到同一个视图!!!
url(r'^upload_pic_handle/',views.upload_pic_handle),
]
views.py
from django.shortcuts import render
from django.conf import settings
import os
from django.http import HttpResponse
def index(request):
return render(request,'booktest/index.html')
#上传图片
def upload_pic(request):
return render(request,'booktest/upload_pic.html')
def upload_pic_handle(request):
pic=request.FILES['up_pic'] 注释:这里是用FILES获得数据不是POST也不是GET!!
file_name = os.path.join(settings.MEDIA_ROOT,pic.name.encode('utf-8'))
with open(file_name,'w') as file:
for c in pic.chunks():
file.write(c)
context = {'pic_name':pic.name}
return render(request,'booktest/upload_pic_handle.html',context)
# return HttpResponse('<img src="/static/media/%s">'%(pic.name)) 这行当初是用来验证用的,省去写html文件的时间
html:
upload_pic.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload_pic</title>
</head>
<body>
这里注意action最后一定要以/结尾!!不然出错,切记
还有这里要有enctype!!切记
<form action="/upload_pic_handle/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="up_pic">
<br>
<input type="submit" value="上传">
</form>
</body>
</html>
upload_pic_handle.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>upload_pic.html_handle</title>
</head>
<body>
<h1>上传成功</h1>
<img src="/static/media/{{pic_name}}" alt="上传图片" style="width:600px">
</body>
</html>
settings.py
部分更改 其他使用默认的就行
更改如下: