django 上传图片接口制作与zui上传图片对接

发表时间:2019-10-23 10:40:26
摘要信息

django上传图片

# 图片上传
def uploadImg(request):
if request.userInfo == None:
data = {
'status': 401,
'msg': '请登录之后,再上传图片哦',
'data': None
}
return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")
img = request.FILES.get('file')
# 判断参数是否齐全
if not img:
data = {
'status': 400,
'msg': '参数不全',
'data': None,
"errno": 1,
}
return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")
user = p_menber.objects.get(username=request.userInfo['username'])
limit = p_sys.objects.get(id=1)
time_local = time.localtime(time.time())
sql_local = time.localtime(float(user.limit_time))
now_time = time.strftime("%Y%m%d", time_local)
sql_time = time.strftime("%Y%m%d", sql_local)
print(int(user.file_limit), int(limit.img_limit))
print(now_time, sql_time)
if now_time != sql_time:
user.limit_time = time.time()
user.msg_limit = 0
user.file_limit = 0
user.save()
else:
if int(user.file_limit) >= int(limit.img_limit):
data = {
'status': 400,
'msg': '您今天长传的图片超过' + str(limit.img_limit) + '次,无法继续上传!',
'data': None,
'type': 'error',
"errno": 1,
}
return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")
fix = str(round(time.time())) + '1'
name = img.name.split('.')
if len(name) == 1:
name = request.POST.get('name').split('.')
print('name', name)
# 对 我们settings中已经配置好的路径 把文件的名称进行存入
img_path = os.path.join(settings.UPLOADFILES_DIRS, fix + str(request.userInfo['id']) + '.' + name[len(name) - 1])
f = open(img_path, 'wb')
for i in img.chunks():
f.write(i)
f.close()

# 入库操作
url = '/static/upload/images/' + fix + str(request.userInfo['id']) + '.' + name[len(name) - 1]
newFile = p_file(name=img.name, path=url, create_time=time.time())
newFile.save()
user.file_limit = user.file_limit+1
user.limit_time = time.time()
user.save()
data = {
'status': 200,
'msg': '上传成功',
'data': [url],
'type': 'success',
"errno": 0,
}
return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")

要先在setting.py中声明图片存储地址

# 上传文件保存路径
UPLOADFILES_DIRS = os.path.join(BASE_DIR, 'static/upload/images')

zui模板中引入js

<link href="{% static '/dist/lib/uploader/zui.uploader.min.css' %}" rel="stylesheet">
<script src="{% static '/dist/lib/uploader/zui.uploader.min.js' %}"></script>
/* 图片上传按钮初始化 */
$('#uploaderExample').uploader({
autoUpload: true, // 当选择文件后立即自动进行上传操作
url: api.uploadImg, // 文件上传提交地址
filters: {
// 只允许上传图片或图标(.ico)
mime_types: [
{title: '图片', extensions: 'jpg,gif,png,jpeg,JPG,JPEG,PNG'},
],
// 最大上传文件为 1MB
max_file_size: '3mb',
// 不允许上传重复文件
prevent_duplicates: true,
},
responseHandler: function (responseObject, file) {
console.log(JSON.parse(responseObject.response))
let data = JSON.parse(responseObject.response)
// 当服务器返回的文本内容包含 `'error'` 文本时视为上传失败
if (data.status != 200) {
new $.zui.Messager(data.msg, {
type: 'danger',
placement: 'center'
}).show();
return '上传失败。服务器返回了一个错误:' + responseObject.response;
} else if (data.status == 200) {
let imgList = JSON.parse($("input[name='m_photo']").val())
imgList.push(data.data[0])
$("input[name='m_photo']").val(JSON.stringify(imgList))
console.log('列表', imgList)
}
}
});



40% Complete (success)