models.py中定义模型
id_image = models.ImageField(upload_to='photos', max_length=255, null=True, blank=True)
# photos是保存图片的文件夹,根目录根据settings.py里设置的MEDIA_ROOT元素来决定,
# 注意:是'photos' 而不是'/photos',区别在于后者是项目根目录下创建photos文件夹,前者是在MEDIA_ROOT对应目录下创建photos
模板a.html中使用(在这里实现了本地预览的效果)
- 应用区域
<img id="preview" alt="" name="img_id_image" src="" width="100" height="100"/>
<a href="javascript:;" class="a-upload">
<input id="f" type="file" name="id_image" onchange="change()" >浏览
</a>
- css效果
/*a upload */
.a-upload {
padding: 4px 10px;
height: 20px;
line-height: 20px;
position: relative;
cursor: pointer;
color: #F8F8F8;
background: #a8a8a8;
border: 1px solid #a8a8a8;
border-radius: 5px;
overflow: hidden;
display: inline-block;
*display: inline;
*zoom: 1
}
.a-upload input {
position: absolute;
right: 0;
top: 0;
opacity: 0;
filter: alpha(opacity=0);
cursor: pointer
}
- js设定
function change() {
var pic = document.getElementById("preview"),
file = document.getElementById("f");
var ext=file.value.substring(file.value.lastIndexOf(".")+1).toLowerCase();
// gif在IE浏览器暂时无法显示
if(ext!='png'&&ext!='jpg'&&ext!='jpeg'){
alert("图片的格式必须为png或者jpg或者jpeg格式!");
return;
}
var isIE = navigator.userAgent.match(/MSIE/)!= null,
isIE6 = navigator.userAgent.match(/MSIE 6.0/)!= null;
if(isIE) {
file.select();
var reallocalpath = document.selection.createRange().text;
// IE6浏览器设置img的src为本地路径可以直接显示图片
if (isIE6) {
pic.src = reallocalpath;
}else {
// 非IE6版本的IE由于安全问题直接设置img的src无法显示本地图片,但是可以通过滤镜来实现
pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")";
// 设置img的src为base64编码的透明图片 取消显示浏览器默认图片
pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
}
}else {
html5Reader(file);
}
}
function html5Reader(file){
var file = file.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e){
var pic = document.getElementById("preview");
pic.src=this.result;
}
}
- 效果图:
views.py中获取和储存
if 'login_name' in request:
id_image = request.FILES.get('id_image')
user.id_image = id_image
这样就好储存到服务器里的photos文件夹里面了。
扩展:如何将服务器里的图片等比例缩放,另存一份,应用于系统其他功能。
id_image = request.FILES.get('id_image')
img = Image.open(id_image)
# 对图片进行等比例缩放
img.thumbnail((500,500),Image.ANTIALIAS)
img.save('picname','png')