django 通过bootstrap fileinput 上传图片

时间:2022-01-19 00:40:42

django 通过bootstrap fileinput 上传图片

实现在django框架下,通过bootstrap前端框架的fileinput控件上传图片

django 1.10.3
bootstrap

1.在app目录下创建图片文件夹

我的项目名称为myproject,我的app名称为myapp,创建的图片存放文件名称为uploadfiles
目录结构如下:
|–myproject
–|–myapp
—–|–urls.py
—–|–uploadfiles
—–|–settings
——–|–dev.py [配置文件]

2.配置文件

在配置文件dev.py中,新增如下代码:

import os

PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
......

# 放置上传的图片
UPLOADFILES = os.path.join(PROJECT_DIR, 'uploadfiles')

3.具体实现

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import time
from PIL import ImageFile
from myproject.settings import dev
from django.http import JsonResponse, HttpResponse

def _upload(file, path):
"""
图片上传函数
"""

if file:
_n = "%d" % (time.time() * 1000)
_f = time.strftime("%Y%m%d", time.localtime())

file_name = _f + _n+".jpg"
path_file = os.path.join(path, file_name)
parser = ImageFile.Parser()
for chunk in file.chunks():
parser.feed(chunk)
img = parser.close()
try:
if img.mode != "RGB":
img = img.convert("RGB")
img.save(path_file, 'jpeg', quality=100)

except:
return None
return file_name
return None


def uploadify_script(request):
"""
通过bootstrap fileinput 上传图片
"""

result = {"data": []}
path = os.path.join(dev.UPLOADFILES)

try:
response = HttpResponse()
response['Content-Type'] = "text/javascript"
ret = -1
file = request.FILES.get("file_data", None)
if file:
imgurl = _upload(file, path)
if not imgurl:
ret = 1
ret = 0
result["imgurl"] = imgurl
result.update(code_msg(ret))
return JsonResponse(result)

except Exception:
return JsonResponse(result)

4.配置路由

在urls.py文件中增:

from django.conf.urls.static import static
from ktv_project.common import uploadimg
from ktv_project.settings.dev import UPLOADFILES
......

"""
上传 图片
"""

urlpatterns += [
url(r'^uploadfiles$', uploadimg.uploadify_script),
]
"""
显示 图片
"""

urlpatterns += static('/uploadfiles/', document_root=UPLOADFILES)

"""

5.前端代码(仅供参考)

JS:

<script>
var res_licenseImg;
$("#file_licenseImg").fileinput({
language: 'zh',
uploadUrl: urlQJ+'/uploadfiles',
allowedFileExtensions : ['jpg', 'png'],
maxFileSize: 5000,
maxFilesNum: 1,
showCaption: false,
showUpload: false,
slugCallback: function(filename) {
return filename.replace('(', '_').replace(']', '_');
}
});

$('#file_licenseImg').on('fileuploaded', function(event, data, previewId, index){
res_licenseImg = data.response.imgurl;
// console.log(res_licenseImg);
if(res_licenseImg){
$('.imgReg').css('display', 'inline')
$('#file_licenseImg').css('display', 'none');
$('.btn-file').css('display', 'none');
}
$('.fileinput-remove').click(function(){
$('#file_licenseImg').css('display', 'inline-block');
$('.btn-file').css('display', 'inline-block');
})
})
</script>

HTML:

<div class="col-sm-8" style="position:relative">
<input id="
file_licenseImg" type="file" class="file" >
<i class="
fa fa-check regII imgReg" style="display:none"></i>
</div>