先说说这个功能吧,这个功能是前端解决了两个月没有都没有解决的问题。我也是实在搞不懂为啥还有脸不离职。
我们先来看前端代码
前端这里我只贴出此种写法,有很多东西还需要你自己完善,申明一下你需要引入jquery和layer的JS文件。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" id="fromId">
{% csrf_token %}
<div style="width: 100%;height: 50px;font-size: 1.3em;line-height: 50px;">
<input type="file" id="user_portrait" name="image" style="margin-left: 10px;">
<button type="button" οnclick="notimages()">点击上传</button>
</div>
<div style="width: 100%;height: 30px;text-align: center;line-height: 30px;font-size: 1.3em;">
图片预览
</div>
<div style="width: 300px;height: 300px;margin: auto;margin-top: 10px;">
<img src="" id="preview" alt="" style="width: 100%;height: 100%;">
</div>
</form>
</body>
</html>
<script>
//图片预览
$(function () {
$('#user_portrait').change(function (e) {
var file = e.target.files[0]||e.dataTransfer.files[0];
if (file){
var reader = new FileReader();
reader.onload = function () {
$('#preview').attr('src',this.result)
};
reader.readAsDataURL(file);
}
})
});
//图片上传
function notimages() {
var formDate = new FormData();
var token = $('input[name=csrfmiddlewaretoken]').val();
var img_file = document.getElementById('user_portrait');
var fileobj = img_file.files[0];
formDate.append('images',fileobj);
formDate.append('csrfmiddlewaretoken',token);
$.ajax({
url : '写上你要上传的路由',
data : formDate,
type : 'POST',
async : false,
dataType : 'json',
processData : false,
contentType : false,
success : function (data) {
if (data.status === 'success') {
layer.msg(data['message'])
} else if (data.status === 'fail') {
layer.msg(data['message']);
}
}
})
}
</script>
下面这是Django的后端代码
from django.shortcuts import HttpResponse
from app.models import Member
import json
import os
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
# 头像上传
@login_required
@csrf_exempt
def uploading(request):
if request.method == 'POST':
try:
# 拿到图片的对象
photo = request.FILES['images']
# 判断图片是否小于2M
if photo.size / 1024 / 1024 < 2:
# 判断图片的格式
if photo.content_type == 'image/jpeg' or photo.content_type == 'image/jpg' or photo.content_type == 'image/png':
# 获取当前格式化时间用于拼接图片名称
nowTime = str(get_timesecond())
# 创建一个文件
path = os.path.join(settings.MEDIA_UPDATA, nowTime + photo.name)
# 写文件 遍历图片文件流
with open(path, 'wb') as f:
for content in photo.chunks():
f.write(content)
# 关闭文件流
f.close()
# 拼接文件名和路径
userima_name = '/static/img/{}'.format(nowTime + photo.name)
# 在数据库中保存上传记录
userid = request.session['member_id']
img = Member.objects.filter(member_id=userid).first()
user_portrait_path = img.member_portrait
# 删除用户之前的头像
if os.path.exists(user_portrait_path):
os.remove(user_portrait_path)
user_new_portrait = Member.objects.filter(user_id=userid).update(member_portrait=userima_name)
if user_new_portrait:
# 返回图片路径
result = {'status': 'success', 'message': '上传成功!', 'img': userima_name}
return HttpResponse(json.dumps(result))
else:
result = {'status': 'fail', 'message': '上传失败!'}
return HttpResponse(json.dumps(result))
else:
result = {'status': 'fail', 'message': '只能上传jpeg、jpg、png格式的图片!'}
return HttpResponse(json.dumps(result))
else:
result = {'status': 'fail', 'message': '上传的文件超过了2M!'}
return HttpResponse(json.dumps(result))
except:
result = {'status': 'failss'}
return HttpResponse(json.dumps(result))
以上就是今天分享的全部内容了,有看不懂的小伙伴们可以给我留言,我会尽量抽出点时间帮助你们。