前端上传组件Plupload使用---上传图片

上传图片到服务器

1.引入js插件:

<script type="text/javascript" src="{{ static_url('plupload/js/plupload.full.min.js') }}"></script>

2.html页面如图:

<label>广告海报:</label>
<a class="btn new_btn-w-m btn-primary" href="#" id="index_image" name="index_image">上传海报
   //给a标签加样式,上传时候显示进度条
   <span id="Progress2" style=" opacity: 0.6;z-index:10; position: absolute; bottom: 0; left: 0; height: 100%; width: 0%; display: block; background-color: #003399"></span>
</a>
<input type="text" name="image" id="image_url" style="display: none">
<span>支持jpg、jpeg、png、gif格式,大小不超过2M.建议尺寸:16X16</span>
<img id="sample" src="" style="margin-top: 10px;max-width: 400px;width: 100%;">
<p class="showInfo"></p>

3.js代码:

<script>
$(function (){
    var uploader_image = new plupload.Uploader({
        browse_button: 'index_image',
        url: "/ajax/upload_image?path=video_img",
    
        filters: {
            max_file_size : '4mb',//最大上传文件大小(格式100b, 10kb, 10mb, 1gb)
            prevent_duplicates : true,
            mime_types: [//允许文件上传类型
                {title: "files", extensions: "jpg,png,gif,jpeg"}
            ]
        },
        multipart_params: {
            '_xsrf': $("input[name='_xsrf']").val()
        },
        init:{
            FilesAdded:function(up, files) {
                plupload.each(files, function (file) {
                    uploader_image.start();
                });
            },
            UploadProgress: function(up, file) { //上传中,显示进度条
                $('#Progress2').css('width', file.percent+'%');
            },
            FileUploaded:function(up, file, info) {
                var base = '/static/media/video_img/';
                var response = $.parseJSON(info.response);
                if (response.status == 'ok') {
                    $("#sample").show().attr("src", base + response.name);
                    $("#image_url").val(response.name);
                }
                else {
                    alert(response.error);
                }
            },
            Error:function(up, errObject) {
                alert(errObject.code+errObject.message);
            },
        }
    });
    uploader_image.init();
});
</script>

 

附加:

<script>
$(function () {
    // editor.sync();
    var uploader = new plupload.Uploader({
        browse_button: 'index_image',
        url: "/ajax/upload_image?path=study_img",

        filters: {
          max_file_size : '4mb',
          prevent_duplicates : true,
        },
        multipart_params: {
            '_xsrf': $("input[name='_xsrf']").val()
        }
    });

    uploader.init();
//        console.log(uploader);

    // 文件添加后立即上传
    uploader.bind('FilesAdded', function (up, files) {
        plupload.each(files, function (file) {
            uploader.start();
        });
    });

    // 上传内容图片
    uploader.bind('FileUploaded', function (up, file, info) {
        var base = '/static/media/study_img/';
        var response = $.parseJSON(info.response);
        if (response.status == 'ok') {
            $("#poster").show().attr("src", base + response.name);
            $("#image_url").val(response.name);
        }
        else {
            alert(response.error);
        }
    });

    uploader.bind('UploadProgress',function(up,file){
        $('#Progress').css('width', file.percent+'%');
    });

    uploader.bind('Error', function (up, errObject) {
        alert(errObject.code+errObject.message);
    });
});
</script>

 

后端代码

1.url路由

(r"/ajax/upload_image", UploadImageFile),


# 下面是全部,上面是简写
class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/ajax/upload_image", UploadImageFile),
            (r"/ajax/upload_video", UploadVideoFile),
        ]
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            upload_path=os.path.join(os.path.dirname(__file__), "static/media"),
            appid="wxdf26791ff0f192e5",
            appsecret="f159318a4cf52422cf7720dae392bf0e",
            timeout=7200,
        )
if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = Application()
    app.listen(options.port)
    print "visit at", "http://0.0.0.0:%s" % options.port
    tornado.ioloop.IOLoop.instance().start()

2.python代码

class UploadImageFile(BaseHandler):
    def post(self):
        path = self.get_argument("path")
        input_name = self.get_argument("iname", "")
        # 得到图片的存储路径upload_path,就是图片文件在哪个文件夹下面
        upload_path = os.path.join(self.settings['upload_path'], path)

        # print path,upload_path
        # 若不存在此目录,则创建之
        if not os.path.isdir(upload_path):
            # upload_path = upload_path.replace("/", "\\") #windows platform
            os.makedirs(upload_path)
        file_metas = self.request.files.get('file', [])
        filename = ''
        try:
            for meta in file_metas:
                filename = meta['filename']
                ext = os.path.splitext(filename)[1]
                # 生成随机文件名
                filename = str(uuid.uuid4())
                filename = '%s%s' % (filename, ext)
                filepath = os.path.join(upload_path, filename)
                with open(filepath, 'wb') as up:
                    up.write(meta['body'])
        except Exception as e:
            print e
            return self.write(json.dumps({"status": 'error', "msg": u"图片上传失败,请重新上传"}))
        else:
            print json.dumps({"status": 'ok', "msg": "", "base_url": "", "name": filename})
            return self.write(json.dumps({"status": 'ok', "msg": "", "base_url": "", "name": filename}))

js获取内容

<script>
    // image的值为:b9be20e9-2837-4adf-b307-f7dfe4f60a9f.jpg
    var xjson = {
        "image": $("#image_url").val(),
        '_xsrf': $("input[name='_xsrf']").val(),
    };
</script>

后台接收内容

def post(self):
    datas = self.request.arguments
    info = dict()
    last = self.db.tb_activity_profile.find_one({}, {"id": 1, "_id": 0}, sort=[("id", pymongo.DESCENDING)])
    info['id'] = int(last.get("id", 0)) + 1 if last else 1
    # 获取的值为:b9be20e9-2837-4adf-b307-f7dfe4f60a9f.jpg
    info['image'] = self.get_argument('image')

在html页面显示图片 

<table class="table table-striped table-bordered table-hover dataTables-example">
    <thead>
    <tr>
        <th><input type="checkbox" class="i-checks" id="userListCheck"/></th>
        <th>活动图片</th>
    </tr>
    </thead>

    <tbody>
    {% for i in activities %}
    {% set avatar = i.get('image') if 'http' in i.get('image') else "/static/media/study_img/"+i.get('image') %}
    <tr class="gradeX">
        <td><input type="checkbox" class="i-checks"></td>
        <td><img src="{{ avatar }}" height="30" width="30"></td>
    </tr>
    {% end %}
    </tbody>
</table>

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值