1. 程式人生 > >plupload.Uploader多文件上傳

plupload.Uploader多文件上傳

alert art pre err mic lda toms contains read

1.前臺CommonUpfile.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CommonUpfile.aspx.cs" Inherits="HraWeb.ETL.CommonUpfile" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="content-type" content="text/html; charset=UTF-8
"/> <title></title> <script type="text/javascript" src="/Scripts/plupload/js/plupload.full.min.js"></script> <style> #container{ margin-left:100px; } button{ width: 100px; height: 50px; background-color: cornflowerblue; }
</style> </head> <body style="font: 13px Verdana; background: #eee; color: #333"> <h1 style="margin-left:50px;">請選擇要導入的文件</h1> <p></p> <div id="filelist"></div> <br /> <div id="container"> <button id="pickfiles" >瀏覽</button> &nbsp;&nbsp;&nbsp;
<button id="uploadfiles" >上傳的文件</button> </div> <br /> <pre id="console"></pre> <script type="text/javascript"> // Custom example logic var uploader = new plupload.Uploader({ runtimes: html5,flash,silverlight,html4, unique_names:true, multipart: true, multi_selection:true, chunk_size: 10mb, browse_button : pickfiles, // you can pass an id... container: document.getElementById(container), // ... or DOM Element itself url: /ETL/CommonUpfile.aspx?_method=upload&callBack=<%=Request["callBack"]%>, flash_swf_url: /Scripts/plupload/js/Moxie.swf, silverlight_xap_url: /Scripts/plupload/js/Moxie.xap, filters : { max_file_size : 1000mb //,mime_types: [ // {title : "Image files", extensions : "jpg,gif,png"}, // {title : "Zip files", extensions : "zip"} //] }, init: { PostInit: function() { document.getElementById(filelist).innerHTML = ‘‘; document.getElementById(uploadfiles).onclick = function() { uploader.start(); return false; }; }, FilesAdded: function(up, files) { plupload.each(files, function(file) { document.getElementById(filelist).innerHTML += <div id=" + file.id + "> + file.name + ( + plupload.formatSize(file.size) + ) <b></b></div>; }); }, UploadProgress: function (up, file) { document.getElementById(file.id).getElementsByTagName(b)[0].innerHTML = <span> + file.percent + "%</span>"; }, Error: function (up, err) { document.getElementById(console).appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message)); }, FileUploaded: function (up, file, res) { //res = JSON.parse(res.response); //art.dialog.close() //artDialog.open.origin.uploadCallBack(file.id,file.name); } , UploadComplete(up,files) { alert("full"); var fileArr = new Array(); for (var i = 0; i < files.length; i++) { var f = new Object(); f.id = files[i].id; f.name = files[i].name; fileArr.push(f); alert(files[i].name+"...") } var fileObj = JSON.stringify(fileArr); $.post("CommonUpfile.aspx?_method=NewImportFile", { fileObj: fileObj }, function (data) { data = JSON.parse(data); $.messager.alert("導入完成",data.Message); artDialog.open.origin.dicCallback(); art.dialog.close(); }); } } }); uploader.init(); $("#console").hide(); </script> <form id="form1" runat="server"> </form> </body> </html> 2.後臺 CommonUpfile.aspx.cs using Contract.Domain; using Contract.IService; using Holworth.BatchingHosting.Interface; using Holworth.Utility; using SocketIM; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.ServiceModel; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace HraWeb.ETL { public partial class CommonUpfile : Common.BasePage { private Contract.IService.IDaoService _dao; Contract.IService.IDaoService Dao { get { if (_dao == null) { _dao = ctx.GetObject("DaoService") as Contract.IService.IDaoService; } return _dao; } } protected void Page_Load(object sender, EventArgs e) { if (Request["_method"] == "upload") { btn_UppLoad(); } else if (Request["_method"] == "NewImportFile") { string fileObj = Request["fileObj"]; var dic = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(fileObj); Dictionary<string, string> idnames = new Dictionary<string, string>(); foreach (var item in dic) { var id = item.id.ToString().Replace("{", "").Replace("}", ""); var name = item.name.ToString().Replace("{", "").Replace("}", ""); idnames[id] = name.ToLower(); } int i = 0; try { string root = Server.MapPath("~/upload"); var mapList = Dao.FindList<EtlDataMap>(new Framework.QueryInfo() { CustomSQL = "select a from EtlDataMap a" }); var mapDict = mapList.ToDictionary(x => x.FileNameStart.ToLower()); string fileName = ""; foreach (var item in idnames) { string ext = Path.GetExtension(item.Value); string fileId = item.Key; fileName = Path.Combine(root, fileId + ext); try { SendFile(fileName, item.Value, mapDict[item.Value.Split(.)[0]].Id); HttpMessages.Instance().PushMessage("導入" + item.Value+"成功"); } catch (Exception ex) { HttpMessages.Instance().PushMessage("導入" + item.Value + "失敗,因為:"+ex.Message); Holworth.Utility.Logger.Fatal(ex); } } var message = new { Message = "導入成功,未導入的文件請查看文件是否在ETL中有定義!!!" }; Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(message)); } catch (Exception ex) { var message = new { ErrorCode = "-1", Message = "導入失敗,因為" + ex.Message }; Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(message)); Holworth.Utility.Logger.Fatal(ex); ; } finally { Response.End(); } } } public void SendFile(string fileName, string fileNameStart, string mapId) { string ipaddr = Holworth.Utility.HraUtility.ConfigurationManager.GetConfig("heartbeatservice", "/Config/ETL.config", HraUtility.IgnoreCase.Ignore); IHeartBeat channel = InvokeContext.CreateWCFServiceByURL<IHeartBeat>(ipaddr, "ws2007HttpBinding", null); ICommunicationObject communicationObject = (ICommunicationObject)channel; try { channel.ClearOldFiles(); int maxBufferLength = 10 * 1024 * 1024; FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); long fileLen = fs.Length; // 文件長度 long totalLen = fileLen; // 未讀取部分 int readLen = 0; // 已讀取部分 byte[] buffer = null; if (fileLen <= maxBufferLength) { /* 文件可以一次讀取*/ buffer = new byte[fileLen]; readLen = fs.Read(buffer, 0, (int)fileLen); channel.Transfer(fileNameStart, buffer); } else { /* 循環讀取文件,並發送 */ while (totalLen != 0) { if (totalLen < maxBufferLength) { buffer = new byte[totalLen]; readLen = fs.Read(buffer, 0, Convert.ToInt32(totalLen)); } else { buffer = new byte[maxBufferLength]; readLen = fs.Read(buffer, 0, maxBufferLength); } channel.Transfer(fileNameStart, buffer); totalLen -= readLen; } } fs.Flush(); fs.Close(); Dictionary<string, string> dic = new Dictionary<string, string>(); dic["DataMap"] = string.Join(",", mapId.Split(,)); dic["FormId"] = Guid.NewGuid().ToString(); var s = Newtonsoft.Json.JsonConvert.SerializeObject(dic); channel.LoadEodFile(s, Guid.NewGuid().ToString()); communicationObject.Close(); } catch (Exception ex) { communicationObject.Abort(); Holworth.Utility.Logger.Fatal(ex); throw; } finally { try { File.Delete(fileName); } catch (Exception exx) { Holworth.Utility.Logger.Fatal(exx); } } } protected void btn_UppLoad() { int statuscode = 1; string message = string.Empty; string filepath = string.Empty; string root = Server.MapPath("~/upload"); List<string> oldFiles = Net.GetFiles(root); //foreach (var item in oldFiles) //{ // if (File.Exists(item)) // { // File.Delete(item); // } //} // string ipaddr = Holworth.Utility.HraUtility.ConfigurationManager.GetConfig("heartbeatservice", "/Config/ETL.config", HraUtility.IgnoreCase.Ignore); // IHeartBeat channel = InvokeContext.CreateWCFServiceByURL<IHeartBeat>(ipaddr, "ws2007HttpBinding", null); // ICommunicationObject communicationObject = //(ICommunicationObject)channel; try { //channel.InitDataNoInit(); //communicationObject.Close(); if (Request.Files != null && Request.Files.Count > 0) { if (Request.Files.Count > 0) { try { string resourceDirectoryName = "upload"; string path = Server.MapPath("~/" + resourceDirectoryName); if (!Directory.Exists(path)) Directory.CreateDirectory(path); int chunk = Request.Params["chunk"] != null ? int.Parse(Request.Params["chunk"]) : 0; //獲取當前的塊ID,如果不是分塊上傳的。chunk則為0 string fileName = Request.Params["name"]; //這裏寫的比較潦草。判斷文件名是否為空。 //if (!fileName.Contains("qwert")) //{ // fileName = $"{Path.GetFileName(fileName).Split(‘.‘)[0]}qwert.dat"; //} string type = 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 (Request.ContentType == "application/octet-stream" && Request.ContentLength > 0) { buffer = new Byte[Request.InputStream.Length]; Request.InputStream.Read(buffer, 0, buffer.Length); } else if (Request.ContentType.Contains("multipart/form-data") && Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) { buffer = new Byte[Request.Files[0].InputStream.Length]; 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 = "保存時發生錯誤,請確保文件有效且格式正確"; Holworth.Utility.Logger.Fatal(ex.Message); } } else { statuscode = -404; message = "上傳失敗,未接收到資源文件"; } string msg = "{\"statusCode\":\"" + statuscode + "\",\"message\":\"" + message + "\",\"filePath\":\"" + filepath + "\"}"; //Response.Write(msg); } } catch (Exception ex) { Holworth.Utility.Logger.Fatal(ex); // communicationObject.Abort(); } finally { //Response.End(); } } IEtlExcelService svc { get { return (IEtlExcelService)ctx.GetObject("EtlExcelService"); } } } }

plupload.Uploader多文件上傳