zoukankan      html  css  js  c++  java
  • 用webuploader上传图片并预览(上传文件)

    1、首先在这个网站下载控件包,并引入网站。

    http://fex.baidu.com/webuploader/?qq-pf-to=pcqq.c2c

    根据网站说明和自己的需求取用不同的文件。

    我是用了这么几个(swf css js 这三个都是要用的,就是看你选择哪个版本,由于我要写jquery来,也引用了jquery):

    2、写jquery函数,来实现,在此我参照了网站和别人写的demo,最终合成了一个既能上传图片并预览的代码。

    红色标记是必须要改的路径,路径别写错

    // 文件上传
    jQuery(function () {
        var $ = jQuery,
            $list = $('#thelist'),
            $btn = $('#ctlBtn'),
            state = 'pending',
             ratio = window.devicePixelRatio || 1,
    // 缩略图大小
    thumbnailWidth = 100 * ratio,
    thumbnailHeight = 100 * ratio,
            uploader;
      
        uploader = WebUploader.create({
    
            // 不压缩image
            resize: false,
    
            // swf文件路径
            swf: 'webUploader/Uploader.swf',
    
            // 文件接收服务端。
            server: '../UploadHandlers.ashx',
            fileNumLimit: 1,//设置可上传文件数量
    
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建,可能是input元素,也可能是flash.
            pick: '#picker',
            // 只允许选择文件,可选。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            }
        });
    
        // 当有文件添加进来的时候
        uploader.on('fileQueued', function (file) {
            var $li = $(
           '<div id="' + file.id + '" class="file-item thumbnail">' +
               '<img>' +
               '<div id="info" runat="server">' + file.name + '</div>' +
                '<p class="state">等待上传...</p>' +
           '</div>'
           ),
       $img = $li.find('img');
    
            $list.append($li);
    
            // 创建缩略图
            uploader.makeThumb(file, function (error, src) {
                if (error) {
                    $img.replaceWith('<span>不能预览</span>');
                    return;
                }
    
                $img.attr('src', src);
            }, thumbnailWidth, thumbnailHeight);
        });
    
        // 文件上传过程中创建进度条实时显示。
        uploader.on('uploadProgress', function (file, percentage) {
            var $li = $('#' + file.id),
                $percent = $li.find('.progress .progress-bar');
    
            // 避免重复创建
            if (!$percent.length) {
                $percent = $('<div class="progress progress-striped active">' +
                  '<div class="progress-bar" role="progressbar" style=" 0%">' +
                  '</div>' +
                '</div>').appendTo($li).find('.progress-bar');
            }
    
            $li.find('p.state').text('上传中');
    
            $percent.css('width', percentage * 100 + '%');
        });
    
        uploader.on('uploadSuccess', function (file) {
            $('#' + file.id).find('p.state').text('已上传');
        });
    
        uploader.on('uploadError', function (file) {
            $('#' + file.id).find('p.state').text('上传出错');
        });
    
        uploader.on('uploadComplete', function (file) {
            $('#' + file.id).find('.progress').fadeOut();
        });
    
        uploader.on('all', function (type) {
            if (type === 'startUpload') {
                state = 'uploading';
            } else if (type === 'stopUpload') {
                state = 'paused';
            } else if (type === 'uploadFinished') {
                state = 'done';
            }
    
            if (state === 'uploading') {
                $btn.text('暂停上传');
            } else {
                $btn.text('开始上传');
            }
        });
    
        $btn.on('click', function () {
            if (state === 'uploading') {
                uploader.stop();
            } else {
                uploader.upload();
            }
            $("#lb").val($("#info").text());//这里是把文件名赋值给标签
        });
    
        
    });
    //下面是鼠标放上去的效果,可以无视
    function mouseO() {
        $("#ctlBtn").addClass("webuploader-pick-hover");
    }
    
    function mouseOt() {
        $("#ctlBtn").removeClass("webuploader-pick-hover");
    }

     3、一般处理程序 ajax接口,用来接收前台提交的图片,上传上去。

    红色标记部分也是必须要改的路径,是用来存图片的

    <%@ WebHandler Language="C#" Class="UploadHandlers" %>
    
    using System;
    using System.Web;
    
    public class UploadHandlers : IHttpHandler {
        
        public void ProcessRequest (HttpContext context) {
            context.Response.ContentType = "text/plain";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            if (context.Request["REQUEST_METHOD"] == "OPTIONS")
            {
                context.Response.End();
            }
            SaveFile();
        }
        private void SaveFile()
        {
            string basePath = "./File/";
            string name;
            basePath = System.Web.HttpContext.Current.Server.MapPath(basePath);
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            if (!System.IO.Directory.Exists(basePath))
            {
                System.IO.Directory.CreateDirectory(basePath);
            }
            var suffix = files[0].ContentType.Split('/');
            //获取文件格式
            //var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];
            var _suffix=suffix[1];
            var _temp = System.Web.HttpContext.Current.Request["name"];
            //如果不修改文件名,则创建随机文件名
            if (!string.IsNullOrEmpty(_temp))
            {
                name = _temp;
            }
            else
            {
                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                name = rand.Next() + "." + _suffix;
            }
            //文件保存
            var full = basePath + name;
            files[0].SaveAs(full);
            var _result = "{"jsonrpc" : "2.0", "result" : null, "id" : "" + name + ""}";
            System.Web.HttpContext.Current.Response.Write(_result);
    
    
        }
    
        public bool IsReusable {
            get {
                return false;
            }
        }
    
    }
    

      4、前台代码

    首先是引用文件

    记得修改路径,fileUpload.js是写的jquery函数的文件

    <script src="/webUploader/jquery-1.7.1.min.js"></script>
        <link href="/webUploader/webuploader.css" rel="stylesheet" />
        <script src="/webUploader/webuploader.nolog.js"></script>
        <script src="/fileUpload.js"></script>

    接下来实现代码

    <div id="uploader" runat="server" class="wu-example">
            <!--用来存放文件信息-->
            <div id="thelist" class="uploader-list"></div>        
            <div class="btns">
            <div id="picker">选择图片</div>
            <div id="ctlBtn" class="webuploader-pick" onmouseover="mouseO();" onmouseout="mouseOt();" >开始上传</div>
            </div>
            <input id="lb" type="hidden" runat="server" />//用标签来存储文件名,试过很多方式,最终认为这种方式比较好
            </div>

    5、后台获取前台文件名

    Request.Form["lb"] 即是标签的值。

    可通过拼接路径来存入数据库。

    基本上只要把路径修改好,就能够直接用了

  • 相关阅读:
    while循环
    赋值运算符、逻辑运算符补充
    布尔类型 基本运算符 if判断
    输入 格式化输出
    计算机基础
    python介绍 编程语言分类及对比 python解释器安装(多版本共存) 变量 数据类型(三种)
    UDP套接字协议
    软件工程个人作业01
    网页版增加信息---添加
    javaWeb项目技术
  • 原文地址:https://www.cnblogs.com/ivan99/p/6642815.html
Copyright © 2011-2022 走看看