Django-上传图片

1.创建app

python manage.py startapp booktest

2.setting添加booktest,配置文件存放位置

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media/')

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    # 2.0以后,反向解析使用以下方式
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

4.配置booktest/urls

from django.urls import path , re_path
from . import views

urlpatterns = [
    re_path(r'^uploadPic$', views.uploadPic),
    re_path(r'^uploadHandle$', views.uploadHandle),

]

注:最新版本2.0以上使用path 或者re_path

 

5.编写视图

from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import os
from django.conf import settings
# from models import *
from django.core.paginator import *
import json
import logging


def uploadPic(request):
    return render(request, 'booktest/uploadPic.html')


def uploadHandle(request):
    pic1 = request.FILES['pic1']
    logging.debug("图片信息:%s " % (pic1.name))
    picName = os.path.join(settings.MEDIA_ROOT, pic1.name)
    # 使用wb+写入二进制,只要w写不进去
    with open(picName, 'wb+') as pic:
        for c in pic1.chunks():
            pic.write(c)
    return HttpResponse('<img src="/static/media/%s"/>' % pic1.name)

6.templates/booktest文件

uploadPic

作者: 温先生

嗨,我是温国力 ,Gerry是我的英文名。一名热衷于编程的开发者,主要专注于PHP、Python、go、区块链的开发。此博客编写了开发心得、读书心得、生活娱乐,随时等待你的关注。

发表评论