溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何利用Plupload.js解決大文件上傳問題

發(fā)布時(shí)間:2021-06-30 15:15:10 來源:億速云 閱讀:209 作者:小新 欄目:web開發(fā)

這篇文章主要介紹如何利用Plupload.js解決大文件上傳問題,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

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

這是一個(gè)Html5統(tǒng)治瀏覽器的時(shí)代,在這個(gè)新的時(shí)代,這種問題已被簡(jiǎn)化并解決,我們可以利用Html5分片上傳的技術(shù),那么Plupload則是一個(gè)對(duì)此技術(shù)進(jìn)行封裝的前端腳本庫(kù),這個(gè)庫(kù)的好處是可以自動(dòng)檢測(cè)瀏覽器是否支持html5技術(shù),不支持再檢測(cè)是否支持flash技術(shù),甚至是sliverlight技術(shù),如果支持,就使用檢測(cè)到的技術(shù)。

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

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

如何利用Plupload.js解決大文件上傳問題

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

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

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

  /******************************************************ProgressBar********************************************************/
      var progressBar = $("#loading").progressbar({ width: '500px', color: '#B3240E', border: '1px solid #000000' });
      /******************************************************Plupload***********************************************************/
      //實(shí)例化一個(gè)plupload上傳對(duì)象
      var uploader = new plupload.Uploader({
        browse_button: 'browse', //觸發(fā)文件選擇對(duì)話框的按鈕,為那個(gè)元素id
        runtimes: 'html5,flash,silverlight,html4',//兼容的上傳方式
        url: "Handlers/UploadCoursePackage.ashx", //后端交互處理地址
        max_retries: 3,   //允許重試次數(shù)
        chunk_size: '10mb', //分塊大小
        rename: true, //重命名
        dragdrop: false, //允許拖拽文件進(jìn)行上傳
        unique_names: true, //文件名稱唯一性

        filters: { //過濾器
          max_file_size: '999999999mb', //文件最大尺寸
          mime_types: [ //允許上傳的文件類型
            { title: "Zip", extensions: "zip" },
            { title: "PE", extensions: "pe" }
          ]
        },
        //自定義參數(shù) (鍵值對(duì)形式) 此處可以定義參數(shù)
        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 單文件上傳 
      });

      //在實(shí)例對(duì)象上調(diào)用init()方法進(jìn)行初始化
      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) {
            //選擇文件以后檢測(cè)服務(wù)器剩余磁盤空間是否夠用
            if (files.length > 0) {
              if (parseInt(files[0].size) > parseInt(result.d)) {
                $('#error-msg').text("文件容量大于剩余磁盤空間,請(qǐng)聯(lián)系管理員!");
              } else {
                $('#error-msg').text("");
              }
            }
          },
          error: function(xhr, err, obj) {
            $('#error-msg').text("檢測(cè)服務(wù)器剩余磁盤空間失敗");
          }
        });
      });

      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("文件上傳失敗,錯(cuò)誤信息: " + err.message);
      });

后臺(tái) 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; //獲取當(dāng)前的塊ID,如果不是分塊上傳的。chunk則為0
          string fileName = context.Request.Params["name"]; //這里寫的比較潦草。判斷文件名是否為空。
          string type = context.Request.Params["type"]; //在前面JS中不是定義了自定義參數(shù)multipart_params的值么。其中有個(gè)值是type:"misoft",此處就可以獲取到這個(gè)值了。獲取到的type="misoft";

          string ext = Path.GetExtension(fileName);
          //fileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), ext);
          filepath = resourceDirectoryName + "/" + fileName;
          fileName = Path.Combine(path, fileName);

          //對(duì)文件流進(jìn)行存儲(chǔ) 需要注意的是 files目錄必須存在(此處可以做個(gè)判斷) 根據(jù)上面的chunk來判斷是塊上傳還是普通上傳 上傳方式不一樣 ,導(dǎo)致的保存方式也會(huì)不一樣
          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 = "保存時(shí)發(fā)生錯(cuò)誤,請(qǐng)確保文件有效且格式正確";

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

再附送一個(gè)檢測(cè)服務(wù)器端硬盤剩余空間的功能吧

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

以上是“如何利用Plupload.js解決大文件上傳問題”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI