plupload.Uploader多文件上传
.前台
<%@ 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>
<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 () {
alert("开始上传");
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')[].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 = ; 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> .后台
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"];
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; 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 = ;
try
{
channel.ClearOldFiles();
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 = "";
idnames.AsParallel().ForAll(item =>
{
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('.')[]].Id);
HttpMessages.Instance().PushMessage("导入" + item.Value + "成功");
}
catch (Exception ex)
{
HttpMessages.Instance().PushMessage("导入" + item.Value + "失败,因为:" + ex.Message);
Holworth.Utility.Logger.Fatal(ex); } });
HttpMessages.Instance().PushMessage("文件传输完毕"); string mapIds = "";
foreach (var item in idnames)
{
mapIds += mapDict[item.Value.Split('.')[]].Id + ",";
}
mapIds = mapIds.TrimEnd(',');
Dictionary<string, string> dic1 = new Dictionary<string, string>();
dic1["DataMap"] = string.Join(",", mapIds.Split(','));
dic1["FormId"] = Guid.NewGuid().ToString();
var s = Newtonsoft.Json.JsonConvert.SerializeObject(dic1);
try
{
channel.LoadEodFile(s, Guid.NewGuid().ToString());
communicationObject.Close();
}
catch (Exception ex)
{
communicationObject.Abort();
} 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
{ int maxBufferLength = * * ;
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
long fileLen = fs.Length; // 文件长度
long totalLen = fileLen; // 未读取部分
int readLen = ; // 已读取部分
byte[] buffer = null; if (fileLen <= maxBufferLength)
{ /* 文件可以一次读取*/
buffer = new byte[fileLen];
readLen = fs.Read(buffer, , (int)fileLen);
channel.Transfer(fileNameStart, buffer);
}
else
{
/* 循环读取文件,并发送 */
while (totalLen != )
{ if (totalLen < maxBufferLength)
{
buffer = new byte[totalLen];
readLen = fs.Read(buffer, , Convert.ToInt32(totalLen));
}
else
{
buffer = new byte[maxBufferLength];
readLen = fs.Read(buffer, , 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 = ;
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 > )
{
if (Request.Files.Count > )
{
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"]) : ; //获取当前的块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 == ? FileMode.OpenOrCreate : FileMode.Append);
//write our input stream to a buffer
Byte[] buffer = null;
if (Request.ContentType == "application/octet-stream" && Request.ContentLength > )
{
buffer = new Byte[Request.InputStream.Length];
Request.InputStream.Read(buffer, , buffer.Length);
}
else if (Request.ContentType.Contains("multipart/form-data") && Request.Files.Count > && Request.Files[].ContentLength > )
{
buffer = new Byte[Request.Files[].InputStream.Length];
Request.Files[].InputStream.Read(buffer, , buffer.Length);
} //write the buffer to a file.
if (buffer != null)
fs.Write(buffer, , buffer.Length);
fs.Close(); statuscode = ;
message = "上传成功"; }
catch (Exception ex)
{
statuscode = -;
message = "保存时发生错误,请确保文件有效且格式正确"; Holworth.Utility.Logger.Fatal(ex.Message);
}
}
else
{
statuscode = -;
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多文件上传的更多相关文章
- plupload+struts2实现文件上传下载
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" ...
- 使用plupload实现多文件上传,自定义参数
下载地址:点击打开链接 1.在开发中可能需要用户附件上传的功能,实现批量上传功能其实就将多个上传任务放到一个集合中,分别上传. 2,使用plupload js插件可以很轻松的实现带参数的多文件上传 3 ...
- asp.net大文件上传与上传文件进度条问题
利用Plupload解决大容量文件上传问题, 带进度条和背景遮罩层 关于Plupload结合上传插件jquery.plupload.queue的使用 这是群里面一位朋友给的资料. 下面是自己搜索到的一 ...
- 实现Magento多文件上传代码功能开发
在Magento中上传单个文件很简单,可以直接在继承的Mage_Adminhtml_Block_Widget_Form类中直接添加如下组件Field: 对于图片: $fieldset->a ...
- 文件上传插件 -- plupload
refresh:重新实例化uploader removeFile(id):从file中移除某个文件 splice(start,length):从队列中start开始删除length个文件, 返回被删除 ...
- Plupload文件上传组件使用API
Plupload有以下功能和特点: 1.拥有多种上传方式:HTML5.flash.silverlight以及传统的<input type=”file” />.Plupload会自动侦测当前 ...
- plupload文件上传插件
一 资源文档 二 基本使用 三 可能遇到的问题 一 资源文档 Git仓库地址:https://github.com/moxiecode/plupload 一个中文速查:http://www.cnblo ...
- angularjs结合plupload实现文件上传
转载注明:(罗志强的博客) angularjs的指令directive非常好使,可以很方便的结合各种插件,实现很强大的功能. 今天用到了plupload,就拿它举例吧. 正常的plupload用法应该 ...
- web 文件上传组件 Plupload
Plupload官网:点击打开链接 建议下载最新版本号,低版本号会出现浏览器兼容问题. 近期公司有个项目须要在web端使用多文件上传功能.刚開始准备使用HTML5来做.但是IE9下面是都不支持的, ...
随机推荐
- 2013年6月编程语言排行榜,C语言位据第一位
2013年6月编程语言排行榜,C语言位据第一位 C语言是很多主流开发语言的母体,.NET的底层,Java的底层都是C开发的,虽然很多新语言来势汹汹,但究其根源,都脱离不开C语言
- python入门-文件
1 读取文件 with open('1.txt') as file_ojbect: contents = file_ojbect.read() print(contents.rstrip()) wit ...
- 好久没玩laravel了,5.6玩下(一)
那么先到官方找到框架,然后安装下 composer安装的,composer怎么安装的 我就不说了 前置条件: PHP >= OpenSSL PHP Extension PDO PHP Exten ...
- Linux命令详解----iostat
Linux系统出现了性能问题,一般我们可以通过top.iostat.free.vmstat等命令来查看初步定位问题.在一个以前看到系统监控工具,总在想那些监控工具的代理,如何收集系统性能信息,io性能 ...
- 使用seaborn制图(箱型图)
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # 设置风格, ...
- YII 使用modules下的css,js,img
用YII assets 1.assets的作用是方便模块化,插件化的,一般来说出于安全原因不允许通过url访问protected下面的文件,但是我们又希望将module单独出来,所以需要使用发布,即将 ...
- maven GroupId 和ArtifactId通常填什么
GroupID是项目组织唯一的标识符,实际对应JAVA的包的结构,是main目录里java的目录结构.ArtifactID就是项目的唯一的标识符,实际对应项目的名称,就是项目根目录的名称.
- Hibernate 的三种状态详解
hibernate的对象有3种状态,分别为:瞬时态(Transient).持久态(Persistent).脱管态(Detached). 处于持久态的对象也称为PO(Persistence Object ...
- 2基本类型数组和枚举类型——重拾Java
2.1 标识符和关键字 2.1.1标识符 标识符:用来标志类名.变量名.方法名.类型名.数组名.文件名的有效字符序列称为标识符.简单地说,标识符就是一个名字. Java关于标识符的语法规则 标识符由字 ...
- 吴裕雄 实战PYTHON编程(9)
import cv2 cv2.namedWindow("ShowImage1")cv2.namedWindow("ShowImage2")image1 = cv ...