Layui框架提供了上传图片的前端实现
- 处理上传图片的
url
为/usr/upload/
- 上传成功后跳转到
/user/set/
if($('.upload-img')[0]){
layui.use('upload', function(upload){
var avatarAdd = $('.avatar-add');
upload.render({
elem: '.upload-img'
,url: '/user/upload/'
,size: 50
,before: function(){
avatarAdd.find('.loading').show();
}
,done: function(res){
if(res.status == 0){
$.post('/user/set/', {
avatar: res.url
}, function(res){
location.reload();
});
} else {
layer.msg(res.msg, {icon: 5});
}
avatarAdd.find('.loading').hide();
}
,error: function(){
avatarAdd.find('.loading').hide();
}
});
});
}
上传图片处理函数
- 表单
name
默认为file
def upload(request):
# 从session中获取当前用户的id
s = request.session.get('userinfo')
uid = s['id']
# 根据id获得对应的用户对象
u = UserInfo.objects.get(id=uid)
# 保存上传的文件
u.photo = request.FILES.get('file')
# 将上传文件保存到DB
u.save()
# 将改变的头像路径写入session
s['photo'] = u.photo.url
request.session['userinfo'] = s
content = {
'status': 0,
}
ret = JsonResponse(content)
return HttpResponse(ret)
- end -