使用WEUI uploader上传图片

使用WEUI uploader上传图片,博主费了很大的劲总算找到完整的了,并且带后台接收代码,有需要的朋友拿去吧,亲测可用!

一、html代码

<link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/0.3.0/weui.css" />


<div class="weui_uploader">
    <div class="weui_uploader_hd weui_cell">
        <div class="weui_cell_bd weui_cell_primary">图片上传</div>
        <div class="weui_cell_ft js_counter">0/6</div>
    </div>
    <div class="weui_uploader_bd">
        <ul class="weui_uploader_files">
            <!-- 预览图插入到这 --> </ul>
        <div class="weui_uploader_input_wrp">
            <input class="weui_uploader_input js_file" type="file" accept="image/jpg,image/jpeg,image/png,image/gif" multiple=""></div>
    </div>
</div>


二、JS代码

$(function () {
    // 允许上传的图片类型
    var allowTypes = ['image/jpg''image/jpeg''image/png''image/gif'];
    // 1024KB,也就是 1MB
    var maxSize = 1024 * 1024;
    // 图片最大宽度
    var maxWidth = 300;
    // 最大上传图片数量
    var maxCount = 6;
    $('.js_file').on('change'function (event) {
        var files = event.target.files;
        // 如果没有选中文件,直接返回
        if (files.length === 0) {
            return;
        }
        for (var i = 0, len = files.length; i < len; i++) {
            var file = files[i];
            var reader = new FileReader();
            // 如果类型不在允许的类型范围内
            if (allowTypes.indexOf(file.type) === -1) {
                $.weui.alert({text: '该类型不允许上传'});
                continue;
            }
            if (file.size > maxSize) {
                $.weui.alert({text: '图片太大,不允许上传'});
                continue;
            }
            if ($('.weui_uploader_file').length >= maxCount) {
                $.weui.alert({text: '最多只能上传' + maxCount + '张图片'});
                return;
            }
            reader.onload = function (e) {
                var img = new Image();
                img.onload = function () {
                    // 不要超出最大宽度
                    var w = Math.min(maxWidth, img.width);
                    // 高度按比例计算
                    var h = img.height * (w / img.width);
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    // 设置 canvas 的宽度和高度
                    canvas.width = w;
                    canvas.height = h;
                    ctx.drawImage(img, 0, 0, w, h);
                    var base64 = canvas.toDataURL('image/png');
                    // 插入到预览区
                    var $preview = $('<li class="weui_uploader_file weui_uploader_status" style="background-image:url(' + base64 + ')"><div class="weui_uploader_status_content">0%</div></li>');
                    $('.weui_uploader_files').append($preview);
                    var num = $('.weui_uploader_file').length;
                    $('.js_counter').text(num + '/' + maxCount);
                    // 然后假装在上传,可以post base64格式,也可以构造blob对象上传,也可以用微信JSSDK上传
                    var progress = 0;
                    function uploading() {
                        $preview.find('.weui_uploader_status_content').text(++progress + '%');
                        if (progress < 100) {
                            setTimeout(uploading, 30);
                        }
                        else {
                            // 如果是失败,塞一个失败图标
                            //$preview.find('.weui_uploader_status_content').html('<i class="weui_icon_warn"></i>');
                            $preview.removeClass('weui_uploader_status').find('.weui_uploader_status_content').remove();
                        }
                    }
                    setTimeout(uploading, 30);
                };
                img.src = e.target.result;
                $.post("/wap/uploader.php", { img: e.target.result},function(res){
                    if(res.img!=''){
                        alert('upload success');
                        $('#showimg').html('<img src="' + res.img + '">');
                    }else{
                        alert('upload fail');
                    }
                },'json');
            };
            reader.readAsDataURL(file);
        }
    });
});


三、PHP代码

$img = isset($_POST['img'])? $_POST['img'] : '';
// 获取图片
list($type$data) = explode(','$img);
// 判断类型
if(strstr($type,'image/jpeg')!=''){
    $ext '.jpg';
}elseif(strstr($type,'image/gif')!=''){
    $ext '.gif';
}elseif(strstr($type,'image/png')!=''){
    $ext '.png';
}
// 生成的文件名
$photo "../upload/".time().$ext;
// 生成文件
file_put_contents($photobase64_decode($data), true);
// 返回
header('content-type:application/json;charset=utf-8');
$res array('img'=>$photo);
echo json_encode($res);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/387108.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

08 面向对象编程

1 介绍 面向对象编程是一种程序设计范式 把程序看做不同对象的相互调用&#xff0c;对现实世界建立对象模型。 面向对象编程的基本思想&#xff1a; 类和实例&#xff1a; 类用于定义抽象类型 实例根据类的定义被创建出来 2 定义类并创建实例 类通过class关键字定义&…

H5+jqweui实现手机端图片压缩上传 Base64

H5jqweui实现手机端图片压缩上传主要功能&#xff0c;使用H5的formData上传base64格式的图片&#xff0c;canvas压缩图片&#xff0c;前端样式使用weui&#xff0c;为方便起见&#xff0c;使用了jquery封装过的weui&#xff0c;jqweui。话不多少&#xff0c;开始上代码。前端代…

09 类的继承

继承一个类 class Person(object): def __init__(self, name, gender): self.name name self.gender gender class Student(Person): def __init__(self, name, gender, score): super(Student, self).__init__(name, gender) self.score score 判断类型 isinstance()可以…

vue 中v-if 与v-show 的区别

相同点或者说功能&#xff0c;都可以动态操作dom元素的显示隐藏 不同点&#xff1a; 1.手段&#xff1a;v-if是动态的向DOM树内添加或者删除DOM元素&#xff1b;v-show是通过设置DOM元素的display样式属性控制显隐&#xff1b;2.编译过程&#xff1a;v-if切换有一个局部编译/卸…

vue打包后放在 nginx部署时候的配置文件

部署了三套程序,默认的&#xff0c;admin和design#user nobody; worker_processes 1;#error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info;#pid logs/nginx.pid;events {worker_connections 1024; }http {include …

淘淘商城之技术选型、开发工具和环境、人员配置

一、技术选型 1&#xff09;Spring、SpringMVC、Mybatis 2&#xff09;JSP、JSTL、jQuery、jQuery plugin、EasyUI、KindEditor&#xff08;富文本编辑器&#xff09;、CSSDIV 3&#xff09;Redis&#xff08;缓存服务器&#xff09; 4&#xff09;Solr&#xff08;搜索&#x…

启动代码格式:nginx安装目录地址 -c nginx配置文件地址

启动启动代码格式&#xff1a;nginx安装目录地址 -c nginx配置文件地址 例如&#xff1a;[rootLinuxServer sbin]# /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf停止nginx的停止有三种方式&#xff1a; 从容停止1、查看进程号[rootLinuxServer ~]# ps -ef…

Lecture 3 Divide and Conquer

1.Divide the problem(instance) into one or more sub-problem; 2.Conquer each sub-problem recursively; 3.Combine solutions.

Maven报错找不到jre

富人之所以越来越富&#xff0c;穷人之所以越来越穷&#xff0c;中产阶级之所以总是在债务泥潭中挣扎&#xff0c;其主要原因之一在于他们对金钱的观念不是来自学校&#xff0c;而是来自家庭。 ---《穷爸爸富爸爸》 一、报错提示 常规配置maven环境变量&#xff0c;报错&#x…

vue按照url地址访问出错404

问题描述&#xff1a; 最近在开发cms的时候使用Vue.js框架&#xff0c;利用vue-route结合webpack编写了一个单页路由项目&#xff0c;自己在服务器端配置nginx。部署完成后&#xff0c;访问没问题&#xff0c;从页面中点击跳转也没问题&#xff0c;但是只要点击刷新或通过浏览器…

Lecture 4 Quick Sort and Randomized Quick Sort

Quick Sort --Divide and Conquer --Sorts “in place” --Very practical with tuning Divide and Conquer: 1.Divide: Partition array into 2 sub-arrays around pivot x such that elements in lower sub-array < x < elements in upper sub-array; 2.Conquer: …

HDU 3966 树链剖分后线段树维护

题意: 一棵树, 操作1.$path(a,b)$之间的点权$k$ 操作2.单点查询 题解: 树链剖分即可,注意代码细节,双向映射 主要是记录一下板子 #include <string.h> #include <stdio.h> #include <algorithm> #define endl \n #define ll long long #define ull unsigned …

VUE config/index.js文件配置

&#xfeff;&#xfeff; 当我们需要和后台分离部署的时候&#xff0c;必须配置config/index.js: 用vue-cli 自动构建的目录里面 &#xff08;环境变量及其基本变量的配置&#xff09;123456789101112131415var path require(path)module.exports {build: {index: path.res…

数据规则列表加导入导出

1.进入bos&#xff0c;打开数据规则&#xff0c;进入列表菜单 2.点击事件-新增操作 3.点击新增 4.点击操作类型&#xff0c;输入%引入 5.点击确定&#xff0c;保存后生效&#xff0c;导出 、引入模板设置同理转载于:https://www.cnblogs.com/RogerLu/p/10643521.html

Lecture 6 Order Statistics

Given n elements in array, find kth smallest element (element of rank k) Worst-case linear time order statistics --by Blum, Floyd, Pratt, Rivest, Tarjan --idea: generate good pivot recursively. Not so hot, because the constant is pretty big.

C++ qsort() 函数调用时实参与形参不兼容的问题解决

《剑指OFFER》刷题笔记 —— 扑克牌顺子 LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)...他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿&#xff01;&#xff01;“红心A…

linux jenkins部署之路之,ftp部署怎么匿名还好用咋解决思密达

怎么安装就不说了&#xff0c;网上一堆 这噶搭是配置 目录是/etc/vsftpd/vsftpd.conf # Example config file /etc/vsftpd/vsftpd.conf# # The default compiled in settings are fairly paranoid. This sample file # loosens things up a bit, to make the ftp daemon more u…

powerCat进行常规tcp端口转发

实战中&#xff0c;我们也会遇到需要我们进行端口转发的情况&#xff0c;比如已经拿下的目标机1是在dmz区&#xff0c;而目标1所在内网的其他目标只能通过目标1去访问&#xff0c;这时候我们就需要端口转发或者代理来进行后渗透。这次就要介绍一个加强版的nc&#xff0c;基于po…

Lecture 7 Hashing Table I

Hash |---Hash function: Division, Multiplication |---Collision: Chaining, Open addressing(Linear,Double hasing) Symbol-table problem: Table S holding n records pointer --> key|satelite data (record) Hashing: Hash function h maps keys “randomly”…