Django项目显示并保存从网页上传的图片

修改settings.py

静态文件夹:

添加:

STATIC_URL = '/assets/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'assets'),
)

动态文件夹:

添加:

MEDIA_ROOT=os.path.join(BASE_DIR,'media').replace('\\','/')
MEDIA_URL = '/media/'

修改urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls'))

]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

添加一句+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

网页实现上传图片

<form action="/upload/" method="POST" enctype="multipart/form-data" >
    {% csrf_token %}
    <div align="center">
    <input type="file" name="testimg"  style="color :white"  >
    </div>

    <div align="center" >
    <input class="inputstyle" type="submit" value="提交"  >
    </div>
</form>

保存图片

    if request.method == 'POST':
        imgs = request.FILES.get('testimg')
        path = default_storage.save(imgs.name,ContentFile(imgs.read()))

在views.py返回图片

return render(request, 'myapp/upload.html',{'images':imgs.name})

在HTML显示图片

<div>
    <img src="/media/{{ images }}" />
    </div>

 

posted @ 2020-05-08 15:51  Jason66661010  阅读(485)  评论(0编辑  收藏  举报