Django2 + python3 上传图片

.
├── db.sqlite3
├── manage.py
├── myImg
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── settings.cpython-36.pyc
│   │   ├── urls.cpython-36.pyc
│   │   └── wsgi.cpython-36.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── static
│   └── media
│       ├── 1493297157_517565.jpg
│       ├── 3.png
│       └── 6.png
├── templates
│   └── myImg
│       ├── showImg.html
│       └── uploadPic.html
└── upLoadImg
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-36.pyc
    │   ├── admin.cpython-36.pyc
    │   ├── models.cpython-36.pyc
    │   └── views.cpython-36.pyc
    ├── admin.py
    ├── apps.py
    ├── migrations
    │   ├── __init__.py
    │   └── __pycache__
    │       └── __init__.cpython-36.pyc
    ├── models.py
    ├── tests.py
    └── views.py

这是一种简单的做法 不需要用到数据库

setting.py中需要配置3个地方

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'upLoadImg',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

STATIC_URL = '/static/'
STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')]
MEDIA_ROOT=os.path.join(BASE_DIR,'static/media')

urls.py

from django.contrib import admin
from django.urls import path
# from myImg.uploadPic import views
from upLoadImg import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('uploadPic/',views.uploadPic),
    path('uploadHandle',views.uploadHandle)
]

views.py

from django.shortcuts import render
from django.conf import settings
from django.http import HttpRequest,HttpResponse
import os
# Create your views here.
def uploadPic(request):
    return render(request,'myImg/uploadPic.html')

def uploadHandle(request):
    if request.method == "POST":
        f1 = request.FILES['pic1']
        fname = os.path.join(settings.MEDIA_ROOT,f1.name)
        with open(fname,'wb+') as pic:
            for c in f1.chunks():
                pic.write(c)
        return HttpResponse('<img src="/static/media/%s" width="500" height="500" alt="图片无法显示"/>'%f1.name) # 这里不给width和height会按图片本身分辨率显示

    else:
        return HttpResponse("error")

    #下面这个是直接显示路径
    # pic1 = request.FILES['pic1']
    # picName=os.path.join(settings.MEDIA_ROOT,pic1.name)
    # return HttpResponse(picName)#/Users/liuwei/myImg/static/media/6.png
    #file:///Users/liuwei/myImg/static/media/6.png
   

 upLoadPic.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/uploadHandle" method="post" enctype="multipart/form-data">
    {% csrf_token %}
<input type="file" name="pic1">
    <br>
    <input type="submit" value="上传">
</form>
</body>
</html>

那进入myImg/目录 运行

python3 manage.py runserver

在浏览器打开

http://127.0.0.1:8000/uploadPic/

碰到几个问题:

1. 图片显示不了 那是因为setting .py中没有

STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')]

2.上传不了 是因为 要用wb+ , 这个百度就可以了

with open(fname,'wb+') as pic:
此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935. 我的gitHub: (学习代码都在gitHub) https://github.com/nwgdegitHub/
原文地址:https://www.cnblogs.com/liuw-flexi/p/9356102.html