国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

利用Plupload.js解決大文件上傳問題, 帶進度條和背景遮罩層

2019-11-19 17:09:10
字體:
來源:轉載
供稿:網友

大容量文件上傳早已不是什么新鮮問題,在.net 2.0時代,HTML5也還沒有問世,要實現這樣的功能,要么是改web.config,要么是用flash,要么是用一些第三方控件,然而這些解決問題的方法要么很麻煩,比如改配置,要么不穩定,比如文件上G以后,上傳要么死掉,要么卡住,通過設置web.config并不能很好的解決這些問題。

這是一個Html5統治瀏覽器的時代,在這個新的時代,這種問題已被簡化并解決,我們可以利用Html5分片上傳的技術,那么Plupload則是一個對此技術進行封裝的前端腳本庫,這個庫的好處是可以自動檢測瀏覽器是否支持html5技術,不支持再檢測是否支持flash技術,甚至是sliverlight技術,如果支持,就使用檢測到的技術。

那么這個庫到哪里下載,怎么搭建呢,比較懶的童鞋還是用Install-Package Plupload搞定吧,一個命令搞定所有事

下面給出一個例子,使用自已定義的控件來使用Plupload (Plupload也有自己的界面可以用),如下

Plupload支持的功能這里就不細說了,什么批量上傳,這里我沒有用到,主要是感覺它支持的事件非常豐富,文件選取后的事件,文件上傳中的事件(可獲得文件的上傳進度),文件上傳成功的事件,文件上傳失敗的事件,等等

我的例子主要是上傳一個單個文件,并顯示上傳的進度條(使用jQuery的一個進度條插件)

下面的例子主要是為文件上傳交給 UploadCoursePackage.ashx 來處理

      /******************************************************ProgressBar********************************************************/      var progressBar = $("#loading").progressbar({ width: '500px', color: '#B3240E', border: '1px solid #000000' });      /******************************************************Plupload***********************************************************/      //實例化一個plupload上傳對象      var uploader = new plupload.Uploader({        browse_button: 'browse', //觸發文件選擇對話框的按鈕,為那個元素id        runtimes: 'html5,flash,silverlight,html4',//兼容的上傳方式        url: "Handlers/UploadCoursePackage.ashx", //后端交互處理地址        max_retries: 3,   //允許重試次數        chunk_size: '10mb', //分塊大小        rename: true, //重命名        dragdrop: false, //允許拖拽文件進行上傳        unique_names: true, //文件名稱唯一性        filters: { //過濾器          max_file_size: '999999999mb', //文件最大尺寸          mime_types: [ //允許上傳的文件類型            { title: "Zip", extensions: "zip" },            { title: "PE", extensions: "pe" }          ]        },        //自定義參數 (鍵值對形式) 此處可以定義參數        multipart_params: {          type: "misoft"        },        // FLASH的配置        flash_swf_url: "../Scripts/plupload/Moxie.swf",        // Silverligh的配置        silverlight_xap_url: "../Scripts/plupload/Moxie.xap",        multi_selection: false //true:ctrl多文件上傳, false 單文件上傳       });      //在實例對象上調用init()方法進行初始化      uploader.init();      uploader.bind('FilesAdded', function (uploader, files) {        $("#<%=fileSource.ClientID %>").val(files[0].name);        $.ajax(        {          type: 'post',          url: 'HardDiskSpace.aspx/GetHardDiskFreeSpace',          data: {},          dataType: 'json',          contentType: 'application/json;charset=utf-8',          success: function (result) {            //選擇文件以后檢測服務器剩余磁盤空間是否夠用            if (files.length > 0) {              if (parseInt(files[0].size) > parseInt(result.d)) {                $('#error-msg').text("文件容量大于剩余磁盤空間,請聯系管理員!");              } else {                $('#error-msg').text("");              }            }          },          error: function(xhr, err, obj) {            $('#error-msg').text("檢測服務器剩余磁盤空間失敗");          }        });      });      uploader.bind('UploadProgress', function (uploader, file) {        var percent = file.percent;        progressBar.progress(percent);      });      uploader.bind('FileUploaded', function (up, file, callBack) {        var data = $.parseJSON(callBack.response);        if (data.statusCode === "1") {          $("#<%=hfPackagePath.ClientID %>").val(data.filePath);          var id = $("#<%=hfCourseID.ClientID %>").val();          __doPostBack("save", id);        } else {          hideLoading();          $('#error-msg').text(data.message);        }      });      uploader.bind('Error', function (up, err) {        alert("文件上傳失敗,錯誤信息: " + err.message);      });

后臺 UploadCoursePackage.ashx 的代碼也重要,主要是文件分片跟不分片的處理方式不一樣

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.IO;namespace WebUI.Handlers{  /// <summary>  /// UploadCoursePackage 的摘要說明  /// </summary>  public class UploadCoursePackage : IHttpHandler  {    public void ProcessRequest(HttpContext context)    {      context.Response.ContentType = "text/plain";      int statuscode = 1;      string message = string.Empty;      string filepath = string.Empty;      if (context.Request.Files.Count > 0)      {        try        {          string resourceDirectoryName = System.Configuration.ConfigurationManager.AppSettings["resourceDirectory"];          string path = context.Server.MapPath("~/" + resourceDirectoryName);          if (!Directory.Exists(path))            Directory.CreateDirectory(path);          int chunk = context.Request.Params["chunk"] != null ? int.Parse(context.Request.Params["chunk"]) : 0; //獲取當前的塊ID,如果不是分塊上傳的。chunk則為0          string fileName = context.Request.Params["name"]; //這里寫的比較潦草。判斷文件名是否為空。          string type = context.Request.Params["type"]; //在前面JS中不是定義了自定義參數multipart_params的值么。其中有個值是type:"misoft",此處就可以獲取到這個值了。獲取到的type="misoft";          string ext = Path.GetExtension(fileName);          //fileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), ext);          filepath = resourceDirectoryName + "/" + fileName;          fileName = Path.Combine(path, fileName);          //對文件流進行存儲 需要注意的是 files目錄必須存在(此處可以做個判斷) 根據上面的chunk來判斷是塊上傳還是普通上傳 上傳方式不一樣 ,導致的保存方式也會不一樣          FileStream fs = new FileStream(fileName, chunk == 0 ? FileMode.OpenOrCreate : FileMode.Append);          //write our input stream to a buffer          Byte[] buffer = null;          if (context.Request.ContentType == "application/octet-stream" && context.Request.ContentLength > 0)          {            buffer = new Byte[context.Request.InputStream.Length];            context.Request.InputStream.Read(buffer, 0, buffer.Length);          }          else if (context.Request.ContentType.Contains("multipart/form-data") && context.Request.Files.Count > 0 && context.Request.Files[0].ContentLength > 0)          {            buffer = new Byte[context.Request.Files[0].InputStream.Length];            context.Request.Files[0].InputStream.Read(buffer, 0, buffer.Length);          }          //write the buffer to a file.          if (buffer != null)            fs.Write(buffer, 0, buffer.Length);          fs.Close();          statuscode = 1;          message = "上傳成功";        }        catch (Exception ex)        {          statuscode = -1001;          message = "保存時發生錯誤,請確保文件有效且格式正確";          Util.LogHelper logger = new Util.LogHelper();          string path = context.Server.MapPath("~/Logs");          logger.WriteLog(ex.Message, path);        }      }      else      {        statuscode = -404;        message = "上傳失敗,未接收到資源文件";      }      string msg = "{/"statusCode/":/"" + statuscode + "/",/"message/":/"" + message + "/",/"filePath/":/"" + filepath + "/"}";      context.Response.Write(msg);    }    public bool IsReusable    {      get      {        return false;      }    }  }}

再附送一個檢測服務器端硬盤剩余空間的功能吧

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using System.Web.Script.Services;using System.Web.Services;using System.Web.UI;using System.Web.UI.WebControls;namespace WebUI{  public partial class CheckHardDiskFreeSpace : System.Web.UI.Page  {    protected void Page_Load(object sender, EventArgs e)    {    }    /// <summary>    /// 獲取磁盤剩余容量    /// </summary>    /// <returns></returns>    [WebMethod]    public static string GetHardDiskFreeSpace()    {      const string strHardDiskName = @"F:/";      var freeSpace = string.Empty;      var drives = DriveInfo.GetDrives();      var myDrive = (from drive in drives        where drive.Name == strHardDiskName        select drive).FirstOrDefault();      if (myDrive != null)      {        freeSpace = myDrive.TotalFreeSpace+"";       }      return freeSpace;    }  }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 枞阳县| 太原市| 利津县| 彝良县| 玉林市| 玛纳斯县| 孝感市| 甘德县| 洞口县| 油尖旺区| 龙海市| 鸡泽县| 美姑县| 宁河县| 青海省| 安顺市| 保亭| 梨树县| 阳江市| 江华| 万盛区| 庆阳市| 黔东| 莒南县| 青田县| 丰宁| 蓬安县| 龙门县| 扬中市| 隆尧县| 开远市| 西青区| 望谟县| 隆昌县| 皋兰县| 舞阳县| 甘南县| 五家渠市| 河池市| 陇西县| 尉犁县|