用webuploader上傳圖片並預覽(上傳文件)

一、首先在這個網站下載控件包,並引入網站。css

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

根據網站說明和本身的需求取用不一樣的文件。web

我是用了這麼幾個(swf css js 這三個都是要用的,就是看你選擇哪一個版本,因爲我要寫jquery來,也引用了jquery):ajax

二、寫jquery函數,來實現,在此我參照了網站和別人寫的demo,最終合成了一個既能上傳圖片並預覽的代碼。數據庫

紅色標記是必需要改的路徑,路徑別寫錯json

 

// 文件上傳
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="width: 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");
}

 

 三、通常處理程序 ajax接口,用來接收前臺提交的圖片,上傳上去。app

紅色標記部分也是必需要改的路徑,是用來存圖片的dom

<%@ 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;
        }
    }

}

  四、前臺代碼函數

首先是引用文件網站

記得修改路徑,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>

五、後臺獲取前臺文件名

Request.Form["lb"] 便是標籤的值。

可經過拼接路徑來存入數據庫。

 

基本上只要把路徑修改好,就可以直接用了

相關文章
相關標籤/搜索