html:
<!-- /.tab-pane -->
<div class="tab-pane" id="head_portrait">
<!-- The timeline -->
<div class="user-block">
<div class="col-sm-2">
<img class="img-circle img-bordered-sm" src="{% static ""%}{% truncate_url request.user.userprofile.head_portrait %}" alt="user image">
</div>
<div class="col-sm-6"><form class="form-horizontal ng-pristine ng-valid" role="form" novalidate="" name="form">
<div class="avatar-local-wrap">
<p style="margin-bottom: 0">从电脑里挑选一张好图作为头像吧</p>
<div class="clearfix">
<input placeholder="选择一个文件" disabled="disabled" class="form-control" style=" 176px;display: inline-block">
<div class="btn btn-default">
<span func="select_upload_file">上传</span>
<input name="file00" type="file" class="hide" form-data="formData" id="startUploadBtn" file-reader="" accept=".jpg,.png,.gif">
</div>
</div>
<div func="msg_error1" class="text-danger hide">对不起,格式错误或文件大小超过2M</div>
<p>支持jpg/png/gif格式图片,文件需小于2M</p>
</div>
<div class="form-group">
<div class="col-sm-offset-0 col-sm-10">
<button type="button" class="btn btn-primary" name="confirm" onclick="UploadFile('#startUploadBtn', 1);">确定</button>
<button type="button" class="btn btn-primary" name="cancel" onclick="UploadFile('#startUploadBtn', 2);">取消</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- /.tab-pane -->
js:
function UploadFile(selector, action){
//上传文件
if(action == 1){
var form_data = new FormData();
//var name = $('#startUploadBtn').val();
//form_data.append('file', $('#startUploadBtn')[0].files[0]);
var name = $(selector).val();
form_data.append('file', $(selector)[0].files[0]);
form_data.append('name', name);
if($(selector)[0].files[0]){
$.ajax({
url: '/auth/userprofile/2/',
type: 'POST',
data: form_data,
//告诉jQuery不要去处理发送的数据
processData : false,
//告诉jQuery不要去设置Content-Type请求头
contentType : false,
//beforeSend: function(){
// console.log('正上传中,请稍候');
//},
success: function(callback){
callback = JSON.parse(callback)['data'];
if(callback['status'] == 1){
//上传图片成功
location.href = window.location.href;
}else if(callback['status'] == 2){
$('div[func="msg_error1"]').removeClass('hide');
$(selector).parent().prev().attr('placeholder', '选择一个文件');
}else{
//上传图片失败
$(selector).parent().prev().attr('placeholder', '选择一个文件');
}
},
error: function(err){
console.log(err);
}
});
}
}else if(action == 2){
//取消上传文件
$('div[func="msg_error1"]').addClass('hide');
$(selector).val('');
$(selector).parent().prev().attr('placeholder', '选择一个文件');
}
}
views.py:
@login_required
def UploadFile(req):
"""
上传文件
:param req:
:return:
"""
data = {'status':0}
if req.method == "POST":
allow_file_type = ['.png', '.jpg', '.gif']
file_obj = req.FILES.get('file') # get的key与 jQurey post中的数据key相同,form_data.append('file', $('#startUploadBtn')[0].files[0]);
# print(file_obj.size, len(file_obj))
# print(dir(file_obj))
file_type = re.findall('.w+$',file_obj.name)[0].lower()
if file_obj and file_type in allow_file_type and len(file_obj) <= 2097152: # 判断文件类型为允许的图片类型且文件大小不超过2M,这里的单位是字节,也可以用file_obj.size变量
file_name = '%s%s%s' %(time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())),random.randrange(10000,99999),file_type)
db_ImageField_file_name = 'upload/user_image/%s' %(file_name) # 组合 UserProfile表中head_portrait字段路径,该字段相当于 字符串字段
# 保存文件,这里边传边写,小于2M的先保存到内存,其他的先保存到系统临时文件,然后再保存到目标文件
with open('upload/user_image/%s' %(file_name),'wb+') as fp:
for chunk in file_obj.chunks():
fp.write(chunk)
user_set = models.UserProfile.objects.filter(user_id=req.user.id)
user_set.update(head_portrait=db_ImageField_file_name)
data['status'] = 1
else:
data['status'] = 2
return HttpResponse(json.dumps({'data':data}))