python django 前端上传图片,后端以二进制流形式保存到数据库

chouliqingke 2020-02-13

models.py

pic = models.BinaryField()

html  ajax 上传请求

$(‘#jbwwtj‘).click(function(){
            var formdata = new FormData();
            formdata.append("wwid",$("#jbwwid").val());
            formdata.append("jbidtp",$(‘input[type=radio][name=jbidtp]:checked‘).val());
            formdata.append("jbwwpic",$("#jbwwpic")[0].files[0]);
            $.ajax({
                url:‘/search/wwjb/‘,
                type:‘POST‘,
                contentType: false,
                processData: false,
                data:formdata,
                success:function(arg){
                    alert(arg)

view.py

pic = request.FILES.get(‘pic‘)   # 获取图片
 img=pic.read()           #将图片转为二进制  ,可直接存储在数据库中
models.pic.objects.create( pic=img)

前端显示操作如下:

views.py

ret=sqlhelp.get_list("select * from home_jb_ww_sh where 1 = 1 limit 10",[])
            for i in range(len(ret)):
                need_base=str(base64.b64encode(ret[i][‘pic‘]))[1:].strip("‘")   #64位编码
                ret[i][‘pic‘]=need_base

html

success:function(data){
                    data=JSON.parse(data);
                    var html=‘‘;
                    for(var i=0;i<data.length;i++){
                        var da=data[i];
                        var nid=i;
                        html +="<div>qq:"+da.ww+"</div><div>类型:"+da.tp+"</div><div>备注:"+da.phone+"</div><div>图片:<img src=‘data:image/png;base64,"+da.pic+"‘/></div><div><input type=‘button‘ value=‘审核通过‘ id=‘"+nid+"‘/><input type=‘button‘ value=‘证据不足‘ id=‘1"+nid+"‘/></div>";
                        <!--$(‘#xstp1‘).attr(‘src‘,‘data:image/png;base64,‘+da.pic)-->
                    }
                    $("#test5").html(html)

相关推荐