1:項目根目錄存放圖片的目錄
2:settings.py 添加
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
3:url.py 添加后面路徑自己定義
import django.views.static
url(r'^media/(?P<path>.*)',django.views.static.serve,{'document_root':'C:\Users\Administrator\PycharmProjects\itracnew\itrac\media'}),
4:views.py
from xxx import settings
def test(request):
if request.method =="POST":
f1 = request.FILES['pic']
fname = '%s/%s' % (settings.MEDIA_ROOT, f1.name)
picname = fname.split(".")[0]+".png"
with open(picname, 'wb') as pic:
for c in f1.chunks():
pic.write(c)
print("picture OK",picname)
post_pic = str(picname.split("/")[1])
5:html文件
<div class="control-group">
<div class="input-group">
<span class="input-group-addon control-label" for="issue">上傳圖片(可選):</span>
<input type="file" name="pic" id="pic" accept="image/*" class="upload-input">
</div>
</div>
6:我在models文件加了一個字段方便存名字調用
pict = models.CharField(max_length=100,null=True,blank=True)
