首页 > 网站 > WEB开发 > 正文

django 通过bootstrap fileinput 上传图片

2024-04-27 15:11:51
字体:
来源:转载
供稿:网友

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 osPROJECT_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 osimport timefrom PIL import ImageFilefrom myproject.settings import devfrom django.http import JsonResponse, HttpResponsedef _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 Nonedef 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 staticfrom ktv_project.common import uploadimgfrom ktv_project.settings.dev import UPLOADFILES......"""上传 图片"""urlpatterns += [ url(r'^uploadfiles$', uploadimg.uploadify_script),]"""显示 图片"""urlpatterns += static('/uploadfiles/', document_root=UPLOADFILES)"""
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表