前端代码
<form method="post" action="{% url 'visit:infoUpload' %}" enctype="multipart/form-data">
{% csrf_token %}
<label for="name">姓 名:</label> <input type="text" placeholder="请输入姓名" id="name" name="name"/><br>
<label for="number">编 号:</label> <input type="number" placeholder="请输入编号" id="number" name="number"/><br>
<label for="idNum">部 门:</label>
<select name="dep">
<option value="技术部">技术部</option>
<option value="行政部">行政部</option>
<option value="销售部">销售部</option>
<option value="董事会">董事会</option>
<option value="访客">访客</option>
</select><br>
<label for="picture">照 片:</label>
<span id="file_warp">
<input type="button" id="button" name="button" value="选择文件" class="addbtn"/>
<input type="file" name="image" id="file1" style="z-index: 1" οnchange="getPhoto(this)"/>
</span><span>(至少1张至多5张)</span><br>
<div class="img_wrap"></div>
<input type="submit" value="确认" id="submit" class="confirm sub"/>
<input type="reset" value="重置" id="reset" style="margin-left: 80px;"/>
</form>
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、多张图片
前端“<input type="file" name="image"/>”多个文件控件名字相同
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')