【Django】 上传图片


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中使用(在这里实现了本地预览的效果)
  1. 应用区域
       
       
    <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>
  2. 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
    }
  3. 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;
    }
    }
  4. 效果图:

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')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值