Django上传图片(包括单张、多图)

前端代码

  
{% csrf_token %}


        (至少1张至多5张)

Django配置

1、views.py文件

from django.db import models

# Create your models here.
class Personnel(models.Model):
    photos = models.ImageField(max_length=255, blank=True, null=True)

2、views.py文件

 
  
# coding:utf-8
import os
from django.shortcuts import render,HttpResponse,HttpResponseRedirect
from visit.models import *

Django上传图片代码(views.py文件下

1、单张图片

def infoUpload(request):
    if request.POST:
      
        img_file = request.FILES.get("image")
        img_name = 'test.jpg'

        f = open(os.path.join('path/', img_name), 'wb')
        for chunk in img_file.chunks(chunk_size=1024):
            f.write(chunk)

   
    return HttpResponseRedirect('/visit/upload)

2、多张图片

前端“”多个文件控件名字相同

def infoUpload(request):
   
    if request.POST:
        img_file = request.FILES.getlist("image")

        for f in img_file:
            destination = open(os.path.join('path/'+ f.name), 'wb')
            for chunk in f.chunks():
                destination.write(chunk)
            destination.close()

    return HttpResponseRedirect('/visit/upload')



你可能感兴趣的:(Django)