Django文件上传【单个/多个图片上传】

准备工作

python:3.6.8
django:2.2.1

新建django项目

 确定项目名称、使用的虚拟环境【当然这个也可以后期修改】、app的名称

创建成功,选择在新的窗口中打开

图片上传

修改配置文件DjangoFileUpload/settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')    #media即为图片上传的根路径

 添加表模型FileUpload/models.py

from django.db import models

class Img(models.Model):
    img_url = models.ImageField(upload_to='photos/',blank=True,null=True) #指定图片上传路径,即media/photos/

数据迁移

python manage.py makemigrations
python manage.py migrate
(django_shop) ------------------------------------------------------------
~/Desktop/DjangoFileUpload » python manage.py makemigrations                                                                                      mosson@bogon
Migrations for 'fileUpload':
  fileUpload/migrations/0001_initial.py
    - Create model Img
(django_shop) ------------------------------------------------------------
~/Desktop/DjangoFileUpload » python manage.py migrate                                                                                             mosson@bogon
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, fileUpload, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying fileUpload.0001_initial... OK
  Applying sessions.0001_initial... OK
(django_shop) ------------------------------------------------------------
~/Desktop/DjangoFileUpload »  

 增加图片上传的路由 DjangoFileUpload/urls.py

from django.contrib import admin
from django.urls import path
from fileUpload import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'uploadImg/',views.uploadImg,name='uploadImg'),
]

 增加图片上传的视图 views.py

from .models import Img

#图片上传
def uploadImg(request):
    if request.method == 'POST':
        img = Img(img_url=request.FILES.get('img'))
        img.save()
    return render(request, 'imgUpload.html')

新增页面templates/imgUpload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片上传</title>
</head>
<body>
    <form action="" method="post" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" name="img">
        <input type="submit" value="上传">
    </form>
</body>
</html>

项目启动

(django_shop) ------------------------------------------------------------
~/Desktop/DjangoFileUpload » python manage.py runserver 0.0.0.0:8008                                                                              mosson@bogon
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
June 20, 2019 - 07:58:37
Django version 2.2.1, using settings 'DjangoFileUpload.settings'
Starting development server at http://0.0.0.0:8008/
Quit the server with CONTROL-C.

 访问页面上传图片

到这里已经完成了。

===============================分割线  多图上传===============================

1 修改imgUpload.html 

把<input type="file" name="img">
改成<input type="file" name="img" multiple="">,就这一处而已,其他都不动

2 views.py

from DjangoFileUpload.settings import BASE_DIR

def uploadImg(request): files = request.FILES.getlist('img') for f in files: destination = open(BASE_DIR + '/media/photos/' + f.name,'wb+') #上传的文件都放到/media/photos/文件夹里 for chunk in f.chunks(): destination.write(chunk) destination.close() return render(request, 'imgUpload.html')  

OK 多图上传已经完成  

=======================码字不易,多多支持===================================

猜你喜欢

转载自www.cnblogs.com/mosson/p/11059149.html