1 页面表单
-
<form role="form" name="upload-pic" id="upload-pic-form" action="/setting/basic/upload" enctype="multipart/form-data" method="post">
-
<div class="change-pic">
-
<a style="text-decoration: none;color: green;">
-
<input type="file" name="upload-pic" id="upload-pic" class="upload-pic" unselectable="on" />更改头像
-
</a>
-
</div>
-
</form>
2 后台逻辑
def _upload_action(self):
if self.request.files:
upload_path = "/home/wangpei/demo/statics/upload/img"
file_metas = self.request.files['upload-pic']
for meta in file_metas:
filename = meta['filename']
str = ''.join([self.current_user,filename])
str_md5 = hashlib.md5(str).hexdigest()
img_name = str_md5[0:16]+'.jpg'
filepath = os.path.join(upload_path,img_name)
with open (filepath,'wb') as up:
up.write(meta['body'])
self.db.execute("UPDATE user SET pic=%s WHERE username=%s",img_name,self.current_user)
self.redirect('/setting/basic')
3 自动提交js
$(function(){
$('#upload-pic').change(function(){
$('#upload-pic-form').submit();
});
});
4 css
.change-pic {
margin-bottom: 0px;
margin-top: -50px;
margin-left: 250px;
height: 30px;
width: 90px;
line-height: 30px;
text-align: center;
font-size: 14px;
cursor: pointer;
border-top-width: 1px;
border-right-width: 1px;
border-bottom-width: 1px;
border-left-width: 1px;
border-top-style: solid;
border-right-style: solid;
border-bottom-style: solid;
border-left-style: solid;
border-top-color: green;
border-right-color: green;
border-bottom-color: green;
border-left-color: green;
-moz-border-left-color: none;
-moz-border-top-color: none;
-moz-border-right-color: none;
-moz-border-bottom-color: none;
border-image-source: none;
border-image-slice: none;
border-image-width: 1 1 1 1;
border-image-outset: 0 0 0 0;
border-image-repeat: stretch stretch;
border-top-left-radius: 50px;
border-top-right-radius: 50px;
border-bottom-left-radius: 50px;
border-bottom-right-radius: 50px;
}
.upload-pic {
opacity: 0;
position: absolute;
display: block !important;
cursor: pointer;
width: 90px;
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/27181165/viewspace-2142975/
,如需转载,请注明出处,否则将追究法律责任。