BS实现文件夹上传下载_终结篇

前两篇《BS文件夹上传操作(二) ——基本功能实现》,《BS文件夹上传操作 》现在来看只能做了解了。真正可以运用到项目中的,只能是这篇ActiveX。

在这里还是要感谢 Left join.G 下。因为没有他的帮忙还不知道这个需求是否能完成。另外这个功能的实现也是我们团队的成果。

Tom,Ryan……两位我心中的高手!

 

 

Web实现文件夹上传,下载功能,具体涉及到两个核心内容ActiveX、WebClient

 

  

一、ActiveX 核心部分 

定义:ActiveX是Microsoft对于一系列策略性 面向对象程序技术和工具的称呼,其中主要的技术是 组件对象模型(COM)。

 

 打开VS

A、新建一个Windows窗体控件库

 

B、项目属性-应用程序-程序集信息

 

C、项目属性-生成

 再把AssemblyInfo.cs添加

[assembly: AllowPartiallyTrustedCallers()]//如果希望程序集被部分受信任的代码调用

 

接下来编码开始 ……

 

核心代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net;
using System.Text.RegularExpressions;
using FumaWindowsLibrary;

namespace WindowsFormsControlLibrary1
{
[Guid("8CA5F4F0-1960-4C30-93F7-6A05A43FAF5E")]
public partial class UserControl1 : UserControl, IObjectSafety
{
public UserControl1()
{
InitializeComponent();
}

/// <summary>
/// 获取选择路径
/// </summary>
/// <returns></returns>
public string OpenFolderdialog()
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
return folderBrowserDialog1.SelectedPath;
}
else
return "";
}



#region IObjectSafety 成员
private const string _IID_IDispatch = "{00020400-0000-0000-C000-000000000046}";
private const string _IID_IDispatchEx = "{a6ef9860-c720-11d0-9337-00a0c90dcaa9}";
private const string _IID_IPersistStorage = "{0000010A-0000-0000-C000-000000000046}";
private const string _IID_IPersistStream = "{00000109-0000-0000-C000-000000000046}";
private const string _IID_IPersistPropertyBag = "{37D84F60-42CB-11CE-8135-00AA004BB851}";

private const int INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001;
private const int INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002;
private const int S_OK = 0;
private const int E_FAIL = unchecked((int)0x80004005);
private const int E_NOINTERFACE = unchecked((int)0x80004002);

private bool _fSafeForScripting = true;
private bool _fSafeForInitializing = true;

public int GetInterfaceSafetyOptions(ref Guid riid, ref int pdwSupportedOptions, ref int pdwEnabledOptions)
{
int Rslt = E_FAIL;

string strGUID = riid.ToString("B");
pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;
switch (strGUID)
{
case _IID_IDispatch:
case _IID_IDispatchEx:
Rslt = S_OK;
pdwEnabledOptions = 0;
if (_fSafeForScripting == true)
pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER;
break;
case _IID_IPersistStorage:
case _IID_IPersistStream:
case _IID_IPersistPropertyBag:
Rslt = S_OK;
pdwEnabledOptions = 0;
if (_fSafeForInitializing == true)
pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_DATA;
break;
default:
Rslt = E_NOINTERFACE;
break;
}

return Rslt;
}

public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions)
{
int Rslt = E_FAIL;
string strGUID = riid.ToString("B");
switch (strGUID)
{
case _IID_IDispatch:
case _IID_IDispatchEx:
if (((dwEnabledOptions & dwOptionSetMask) == INTERFACESAFE_FOR_UNTRUSTED_CALLER) && (_fSafeForScripting == true))
Rslt = S_OK;
break;
case _IID_IPersistStorage:
case _IID_IPersistStream:
case _IID_IPersistPropertyBag:
if (((dwEnabledOptions & dwOptionSetMask) == INTERFACESAFE_FOR_UNTRUSTED_DATA) && (_fSafeForInitializing == true))
Rslt = S_OK;
break;
default:
Rslt = E_NOINTERFACE;
break;
}

return Rslt;
}

#endregion
}
}

接口IObjectSafety.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace FumaWindowsLibrary
{
[ComImport, GuidAttribute("CB5BDC81-93C1-11CF-8F20-00805F2CD064")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IObjectSafety
{
[PreserveSig]
int GetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] ref int pdwSupportedOptions, [MarshalAs(UnmanagedType.U4)] ref int pdwEnabledOptions);

[PreserveSig()]
int SetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] int dwOptionSetMask, [MarshalAs(UnmanagedType.U4)] int dwEnabledOptions);
}
}



核心部分运行效果:

 

 

 如果你的项目要引用ActiveX 具体内容可baidu,google 就知道了……

 

 

 

 二、WebClient

 

MSDN: WebClient 类提供向 URI 标识的任何本地、Intranet 或 Internet 资源发送数据以及从这些资源接收数据的公共方法。

核心是Asp.Net 站点文件传输

1。  发起端:

System.Net.WebClient webclient = new System.Net.WebClient();
webclient.UploadFile(filePath, "POST", fileuri);//filePath接收端地址 eg:FolderUploader.ashx

 2。接收端(FolderUploader.ashx)

void Page_Load(object sender, EventArgs e)
{

 foreach(string f in Request.Files.AllKeys)
   {
         HttpPostedFile file = Request.Files[f]; file.SaveAs(@"c:\" + file.FileName); 
   }
 }

 

 

如果你的项目中有类似的需求,上面的那过去再自由发挥下其他,基本上OK!

 

 

以上,可以根据自己的需求实现文件夹上传,下载(单个文件上传下载直接拖拽控件)

 

 

再看看我们的项目及功能实现                                                                        

   思路决定出路

不管做什么,思想最重要,有了想法就会有方法,大体说下我们所用到的思路……

导入:在ActivceX中当用户选择某一文件夹,先查找该文件夹下的文件及文件夹(递归查找)再组合成Table最后循环Table并调用WebClient.UploadFile方法(UploadFile:将本地文件发送到资源并返回包含任何响应的字节数组)实现文件夹上传功能。

导出:则需要通过客户端选择下载的路径以参数形式传递到ActiveX中,导出可分两种:文件、文件夹

  文件:单个文件,则直接传递文件的绝对路径。DownloadFile(filePath, selectPath)//selectPath文件的绝对保存路径 filePath文件被下载的路径

  文件夹:文件夹复杂些,因为文件夹中可能包含文件,文件夹……在客户端把文件夹(递归)以json格式传递到ActiveX中并转换成Table并进行相关导出工作

 

如果不清楚,看看下面代码

一、AvtiveX

进行了一些扩展,另外接口还是上面的IObjectSafety

View Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net;
using System.Text.RegularExpressions;


namespace WindowsLibrary
{
[Guid("8CA5F4F0-1960-4C30-93F7-6A05A43FAF5E")]
public partial class FoldDialog : UserControl, IObjectSafety
{
public string Ticking { get; set; }

public FoldDialog()
{
InitializeComponent();
}
#region 文件夹导入
/// <summary>
/// 导入
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public string OpenFolderdialog(string filePath)
{
var dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("ParName");
dt.Columns.Add("Size");
dt.Columns.Add("Type");
dt.Columns.Add("Url");

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
DirectoryInfo dirInfo = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
DataRow dr = dt.NewRow();
dr["Name"] = dirInfo.Name;
dr["Type"] = "Folder";
dt.Rows.Add(dr);

dt = GetFolderChildList(dt, dirInfo);
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["Url"] != DBNull.Value && !string.IsNullOrEmpty(dt.Rows[i]["Url"].ToString()))
{
string fileuri = dt.Rows[i]["Url"].ToString();
System.Net.WebClient webclient = new System.Net.WebClient();
webclient.UploadFile(filePath, "POST", fileuri);
}
}
return ToJson(dt);
}
else
return "";
}
private DataTable GetFolderChildList(DataTable folderDt, DirectoryInfo dirInfo)
{
FileSystemInfo[] childrenList = dirInfo.GetFileSystemInfos();
foreach (var childInfo in childrenList)
{
DataRow dr = folderDt.NewRow();
if (childInfo is DirectoryInfo)
{
dr["Name"] = childInfo.Name;
dr["ParName"] = dirInfo.Name;
dr["Type"] = "Folder";
}
if (childInfo is FileInfo)
{
byte[] file = FileToBinary(childInfo.FullName);
dr["Name"] = childInfo.Name;
dr["ParName"] = dirInfo.Name;
dr["Size"] = file.Length;
dr["Type"] = childInfo.Extension;
dr["Url"] = childInfo.FullName;
}
folderDt.Rows.Add(dr);
if (childInfo is DirectoryInfo)
GetFolderChildList(folderDt, childInfo as DirectoryInfo);
}

return folderDt;
}
#endregion

#region 文件夹导出
/// <summary>
/// 导出
/// </summary>
/// <returns></returns>
public string FileExport(string path)
{
string selectPath = "";
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string[] pathList = path.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

selectPath = folderBrowserDialog1.SelectedPath;
selectPath += @"\ExportOut\";
if (Directory.Exists(selectPath))
{
return ("该导出路径:'" + selectPath + "'已存在,请选用其他导出路径!");
}
else
Directory.CreateDirectory(selectPath);

if (pathList.Length > 2 && pathList[2] == "文件")//文件
{
string fileName = pathList[1]; //被下载的文件名
string filePath = pathList[0];//被下载路径
WebClient client = new WebClient();
selectPath = selectPath + "\\" + fileName; //文件保存的绝对路径+文件名
try
{
WebRequest myre = WebRequest.Create(filePath);
}
catch (Exception ex)
{
return "错误:" + ex.Message;
}
try
{
client.DownloadFile(filePath, selectPath);
return "导出成功!";
}
catch (Exception ex)
{
return "错误:" + ex.Message;
}
}
else //文件夹
{
DataTable dt = JsonToDataTable(pathList[0]);
return GerFolderAndFile(dt, "", selectPath, pathList[1]);

}
}

return "";

}


/// <summary>
/// 递归文件夹中文件及文件夹
/// </summary>
/// <param name="dt"></param>
/// <param name="parFuId"></param>
/// <param name="selectPath"></param>
/// <param name="servicePath"></param>
/// <returns></returns>
private string GerFolderAndFile(DataTable dt, string parFuId, string selectPath, string servicePath)
{
DataRow[] drRow;
if (string.IsNullOrEmpty(parFuId))
drRow = dt.Select("ParFUID='' ");
else
drRow = dt.Select(" ParFUID='" + parFuId + "'");
foreach (DataRow row in drRow)
{
if (row["FileType"] == DBNull.Value || string.IsNullOrEmpty(row["FileType"].ToString()))
{
string path = selectPath + row["FileName"] + @"\";//创建文件夹路径

if (Directory.Exists(path))
{
return ("该导出路径:'" + selectPath + "'已存在,请选用其他导出路径!"); ;
}
else
Directory.CreateDirectory(path);
parFuId = row["FUID"].ToString();
GerFolderAndFile(dt, parFuId, path, servicePath);
}
else
{
string fileName = row["FileName"].ToString(); //被下载的文件名
string filePath = servicePath + ("/" + row["FileSavePath"].ToString() + "/" + row["FileSaveName"]).Replace("\\", "/");//被下载路径

// selectPath导出路径
selectPath = selectPath + fileName; //文件保存的绝对路径+文件名
WebClient client = new WebClient();
try
{
WebRequest myre = WebRequest.Create(filePath);
}
catch (Exception ex)
{
return ex.Message;
}
try
{
client.DownloadFile(filePath, selectPath);
return "导出成功";
}
catch (Exception ex)
{
return "错误:" + ex.Message;
}
//
}
}
return "导出成功";
}
#endregion

/// <summary>
/// 将文件转换为二进制流进行读取
/// </summary>
/// <param name="fileName">文件完整名路径</param>
/// <returns>文件二进制流</returns>
public byte[] FileToBinary(string fileName)
{
FileStream fsRead = new FileStream(fileName, FileMode.Open, FileAccess.Read);
try
{
if (fsRead.CanRead)
{
int fsSize = Convert.ToInt32(fsRead.Length);
byte[] btRead = new byte[fsSize];
fsRead.Read(btRead, 0, fsSize);
return btRead;
}
else
{
throw new Exception("文件读取错误!");
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
fsRead.Close();
}
}
#region Json

#region dataTable转换成Json格式
/// <summary>
/// dataTable转换成Json格式
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
private string ToJson(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{\"");
jsonBuilder.Append(dt.TableName);
jsonBuilder.Append("\":[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\":\"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("\",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("},");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}

#endregion dataTable转换成Json格式

#region DataSet转换成Json格式
/// <summary>
/// DataSet转换成Json格式
/// </summary>
/// <param name="ds">DataSet</param>
/// <returns></returns>
private string ToJson(DataSet ds)
{
StringBuilder json = new StringBuilder();

foreach (DataTable dt in ds.Tables)
{
json.Append("{\"");
json.Append(dt.TableName);
json.Append("\":");
json.Append(ToJson(dt));
json.Append("}");
}
return json.ToString();
}
#endregion

#region 将获取的Json数据转换为DataTable
/// <summary>
/// 将获取的Json数据转换为DataTable
/// </summary>
/// <param name="strJson">Json字符串</param>
/// <returns></returns>
public static DataTable JsonToDataTable(string strJson)
{
//取出表名
var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
string strName = rg.Match(strJson).Value;
DataTable tb = null;
//去除表名
strJson = strJson.Substring(strJson.IndexOf("[") + 1);
strJson = strJson.Substring(0, strJson.IndexOf("]"));

//获取数据
rg = new Regex(@"(?<={)[^}]+(?=})");
MatchCollection mc = rg.Matches(strJson);
for (int i = 0; i < mc.Count; i++)
{
string strRow = mc[i].Value;
string[] strRows = strRow.Split(',');

//创建表
if (tb == null)
{
tb = new DataTable();
tb.TableName = strName;
foreach (string str in strRows)
{
var dc = new DataColumn();
string[] strCell = str.Split(':');
dc.ColumnName = strCell[0].Replace("\"", "");// strCell[0];
tb.Columns.Add(dc);
}
tb.AcceptChanges();
}

//增加内容
DataRow dr = tb.NewRow();
for (int r = 0; r < strRows.Length; r++)
{
dr[r] = strRows[r].Split(':')[1].Trim().Replace("", ",").Replace("", ":").Replace("\"", "");
}
tb.Rows.Add(dr);
tb.AcceptChanges();
}

return tb;
}

#endregion

#endregion
#region IObjectSafety 成员
private const string _IID_IDispatch = "{00020400-0000-0000-C000-000000000046}";
private const string _IID_IDispatchEx = "{a6ef9860-c720-11d0-9337-00a0c90dcaa9}";
private const string _IID_IPersistStorage = "{0000010A-0000-0000-C000-000000000046}";
private const string _IID_IPersistStream = "{00000109-0000-0000-C000-000000000046}";
private const string _IID_IPersistPropertyBag = "{37D84F60-42CB-11CE-8135-00AA004BB851}";

private const int INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001;
private const int INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002;
private const int S_OK = 0;
private const int E_FAIL = unchecked((int)0x80004005);
private const int E_NOINTERFACE = unchecked((int)0x80004002);

private bool _fSafeForScripting = true;
private bool _fSafeForInitializing = true;

public int GetInterfaceSafetyOptions(ref Guid riid, ref int pdwSupportedOptions, ref int pdwEnabledOptions)
{
int Rslt = E_FAIL;

string strGUID = riid.ToString("B");
pdwSupportedOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER | INTERFACESAFE_FOR_UNTRUSTED_DATA;
switch (strGUID)
{
case _IID_IDispatch:
case _IID_IDispatchEx:
Rslt = S_OK;
pdwEnabledOptions = 0;
if (_fSafeForScripting == true)
pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_CALLER;
break;
case _IID_IPersistStorage:
case _IID_IPersistStream:
case _IID_IPersistPropertyBag:
Rslt = S_OK;
pdwEnabledOptions = 0;
if (_fSafeForInitializing == true)
pdwEnabledOptions = INTERFACESAFE_FOR_UNTRUSTED_DATA;
break;
default:
Rslt = E_NOINTERFACE;
break;
}

return Rslt;
}

public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions)
{
int Rslt = E_FAIL;
string strGUID = riid.ToString("B");
switch (strGUID)
{
case _IID_IDispatch:
case _IID_IDispatchEx:
if (((dwEnabledOptions & dwOptionSetMask) == INTERFACESAFE_FOR_UNTRUSTED_CALLER) && (_fSafeForScripting == true))
Rslt = S_OK;
break;
case _IID_IPersistStorage:
case _IID_IPersistStream:
case _IID_IPersistPropertyBag:
if (((dwEnabledOptions & dwOptionSetMask) == INTERFACESAFE_FOR_UNTRUSTED_DATA) && (_fSafeForInitializing == true))
Rslt = S_OK;
break;
default:
Rslt = E_NOINTERFACE;
break;
}

return Rslt;
}

#endregion
}

}

 

客户端web页面

 

 前台代码

 

View Code
<%--FolderUpLoad--%>
<object id="UserControl1" classid="clsid:8CA5F4F0-1960-4C30-93F7-6A05A43FAF5E" width="1"
height
="0.01">
</object>

这里的clsid是不是很眼熟?不要弄错就是ActiveX中GUID

View Code
 <ext:Button ID="btnBrowseFolderIn" Icon="ArrowDown" Text="导入" runat="server">
<Listeners>
<Click Handler="BrowseFolderIn();" />
</Listeners>
</ext:Button>
<ext:Button ID="btnBrowseFolderOut" Icon="ArrowUp" Text="导出" runat="server">
<Listeners>
<Click Handler="BrowseFolderOut();" />
</Listeners>
</ext:Button>

JS

  <script language="javascript" type="text/javascript">
//导入
function BrowseFolderIn() {
try {
if (!document.all){
alert("请使用IE浏览器");
return;
}
Ext.net.DirectMethods.BrowseFolderIn(
{
success: function(result) {
if (result != "") {
if (result == "-1") {
Ext.Msg.alert('提示', "不允许根目录导入");
return;
}
if (result == "-2") {
Ext.Msg.alert('提示', "该目录不存在");
return;
}
}
var userControl = document.getElementById("UserControl1"); //ActiveX
var filepath = hdFilePath.getValue()+"?type="+result;
var path = userControl.OpenFolderdialog(filepath);
Ext.net.DirectMethods.BrowseFolderInService(path);//文件保存数据库
},
failure: function(errorMsg) {
Ext.Msg.alert('Failure', errorMsg);
}
}
);
} catch (e) {
alert(e.message);
}
}


//导出
function BrowseFolderOut() {
try {
if (!document.all) {
alert("请使用IE浏览器");
return;
}
Ext.net.DirectMethods.BrowseFolderOut(
{
success: function(result) {
if (result != "") {
if (result == "-1") {
Ext.Msg.alert('提示', "不允许根目录导出");
return;
}
if (result == "-2") {
Ext.Msg.alert('提示', "该目录不存在");
return;
}
if (result == "-3") {
Ext.Msg.alert('提示', "该文件不存在");
return;
}
}
var userControl = document.getElementById("UserControl1"); //ActiveX
var folderOut = userControl.FileExport(result);
Ext.Msg.alert('提示', folderOut);
},
failure: function(errorMsg) {
Ext.Msg.alert('Failure', errorMsg);
}
}
);
} catch (e) {
alert(e.message);
}
}

</script>


导入

View Code
        #region 导入
/// <summary>
/// 导入->判断
/// </summary>
/// <param name="importPath">导入文件路径</param>
[DirectMethod]
public string BrowseFolderIn()
{
string parFuid = hdFolderFid.Value.ToString();
if (string.IsNullOrEmpty(parFuid) || parFuid == "00000000-0000-0000-0000-000000000000")
return "-1";//不允许根目录导出
DcFolder fold = new DcFolder(parFuid);
if (fold.ParFUID == null)
return "-2";//该目录不存在
string fileSavePath = ConfigurationManager.AppSettings["FileUploadPath"];//上传路径
string uploadPath = Server.MapPath(fileSavePath);//服务器相对上传路径
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
if ((int)fold.DirType < 3)//公司
return "1";
if ((int)fold.DirType == 3)//个人
return "2";
return "0";
}
/// <summary>
/// 导入->确定 方法
/// </summary>
/// <param name="sourcePath"></param>
[DirectMethod]
public void BrowseFolderInService(string sourcePath)
{
try
{
DataTable dt = JSONHelper.JsonToDataTable(sourcePath);
FolderHelper fh = new FolderHelper();
string parFuid = hdFolderFid.Value.ToString();
string fileSavePath = string.Empty;
string time = DateTime.Now.ToShortDateString();
DcFolder fold = new DcFolder(parFuid);
if ((int)fold.DirType < 3)//公司
{
fileSavePath = ConfigurationManager.AppSettings["FileUploadPathCompanyDoc"];//保存数据库路径
fileSavePath += time;
}
if ((int)fold.DirType == 3)//个人
{
fileSavePath = ConfigurationManager.AppSettings["FileUploadPathPrivateDoc"];//保存数据库路径
fileSavePath += time;
}
if (dt != null)
{
Folder(dt, "", parFuid, fileSavePath);
}
BindFolderAndFileList((int)fold.DirType, parFuid, "admin"); //上传成功再次加载
UpdateFileName();
}
catch (Exception)
{
return;
}
}
/// <summary>
/// 递归文件夹中文件及文件夹
/// </summary>
/// <param name="dt"></param>
/// <param name="name"></param>
/// <param name="parFuid"></param>
/// <param name="fileSavePath"></param>
private void Folder(DataTable dt, string name, string parFuid, string fileSavePath)
{
FolderHelper fh = new FolderHelper();
DataRow[] drRow;
if (string.IsNullOrEmpty(name))
drRow = dt.Select("ParName='' ");
else
drRow = dt.Select(" ParName='" + name + "'");
foreach (DataRow row in drRow)
{
if (row["Url"] == DBNull.Value || string.IsNullOrEmpty(row["Url"].ToString()))
{
string childFuid = fh.CreateFold(parFuid, row["Name"].ToString());
name = row["Name"].ToString();
Folder(dt, name, childFuid, fileSavePath);
}
else
{
string fileName = row["Name"].ToString();
string extension = row["Type"].ToString();
string fileSaveName = _fileManager.GetFileSaveName();
fileSaveName += extension;
int length = Convert.ToInt32(row["Size"].ToString());
fileSavePath = fileSavePath.Replace("/", @"\");
_fileManager.AppendFileToBaseManager(parFuid, fileName, extension, fileSavePath, fileSaveName, length);
Thread.Sleep(50);
}
}
}
/// <summary>
/// 根据数据库文件名修改目录下文件名
/// </summary>
private void UpdateFileName()
{
string keyId = "admin";
DataTable dtFile = _fileManager.GetFileInfoByKeyId(keyId);
if (dtFile == null || dtFile.Rows.Count < 0)
return;
string filePath = string.Empty;
FileInfo fi;

foreach (DataRow row in dtFile.Rows)
{
filePath = Server.MapPath(@"\" + row["FileSavePath"] + @"\" + (keyId + row["FileName"]));
fi = new FileInfo(filePath);
if (fi.Exists)
{
string destFileName = Server.MapPath((@"\" + row["FileSavePath"] + @"\" + row["FileSaveName"]));
if (!File.Exists(destFileName))
{
fi.MoveTo(destFileName);
}
}
}
}
#endregion

导出

View Code
        #region 导出
/// <summary>
/// 导出->判断
/// </summary>
/// <returns></returns>
[DirectMethod]
public string BrowseFolderOut()
{
string parFuid = hdFolderFid.Value.ToString();
//文件夹
if (string.IsNullOrEmpty(parFuid) || parFuid == "00000000-0000-0000-0000-000000000000")
return "-1";
DcFolder fold = new DcFolder(parFuid);//文件夹
DataSet dsFile = _fileManager.GetFileByID(parFuid);//文件
if (fold.ParFUID == null && (dsFile == null || dsFile.Tables.Count <= 0 || dsFile.Tables[0].Rows.Count <= 0))
return "-2";//该目录不存在
//else if (dsFile == null || dsFile.Tables.Count <= 0 || dsFile.Tables[0].Rows.Count <= 0)
// return "-3";//该文件不存在

string readPath = string.Empty;//服务器读取路径
if (dsFile != null && dsFile.Tables.Count > 0 && dsFile.Tables[0].Rows.Count > 0)//文件
{
DataTable dtFile = dsFile.Tables[0];
readPath = "/" + dtFile.Rows[0]["FileSavePath"].ToString() + "/" + dtFile.Rows[0]["FileSaveName"].ToString();
readPath = ConfigurationManager.AppSettings["ServicePath"] + readPath.Replace("\\", "/");
readPath += "|" + dtFile.Rows[0]["FileName"].ToString() + "|文件";
return readPath;
}
else if (fold.ParFUID != null)//文件夹
{
DataTable dtFile = new DataTable();
dtFile.Columns.Add("FileName");
dtFile.Columns.Add("FUID");
dtFile.Columns.Add("ParFUID");
dtFile.Columns.Add("FileSize");
dtFile.Columns.Add("FileType");
dtFile.Columns.Add("OwnerID");

dtFile.Columns.Add("FileSavePath");
dtFile.Columns.Add("FileSaveName");
dtFile.Columns.Add("FileTypeName");
dtFile.Columns.Add("KeyInID");
dtFile.Columns.Add("DirType");

DataRow dr = dtFile.NewRow();
dr["FUID"] = parFuid;
//dr["ParFUID"] = fold.ParFUID;
dr["FileName"] =fold.DirName;
dr["KeyInID"] = fold.KeyInID;
dr["OwnerID"] = fold.OwnerID;
dr["DirType"] = fold.DirType;
dtFile.Rows.Add(dr);
dtFile = GerFolderAndFile(dtFile, parFuid, Convert.ToInt32(fold.DirType), "admin");
string json = JSONHelper.ToJson(dtFile) + "|" + ConfigurationManager.AppSettings["ServicePath"];
return json;
}
else
{
Common.CommonMethod.Show("提示", "该目录不存在", MessageBox.Icon.WARNING);
return "-2";
}
}
/// <summary>
/// 获取文件夹下所有子文件及相关文件夹
/// </summary>
/// <param name="folderDt"></param>
/// <param name="parFuId"></param>
/// <param name="type"></param>
/// <param name="empID"></param>
/// <returns></returns>
public DataTable GerFolderAndFile(DataTable folderDt, string parFuId, int type, string empID)
{
DataTable dtFile = _fileManager.GetFolderAndFileList(parFuId, type, empID);
if (dtFile == null || dtFile.Rows.Count < 0)
{
return null;
}
FolderHelper folder = new FolderHelper();
foreach (DataRow row in dtFile.Rows)
{
DataRow dr = folderDt.NewRow();
if (row["FileTypeName"].ToString() == "文件夹")
{
dr["FUID"] = row["FUID"];
dr["ParFUID"] = parFuId;// row["ParFUID"];
dr["FileName"] = row["FileName"];
dr["FileSize"] = row["FileSize"];
//dr["FileType"] = row["FileType"];
dr["OwnerID"] = row["OwnerID"];
dr["FileSavePath"] = row["FileSavePath"];
dr["FileSaveName"] = row["FileSaveName"];
dr["FileTypeName"] = row["FileTypeName"];
dr["KeyInID"] = row["KeyInID"];
dr["DirType"] = row["DirType"];
string childFuId = dr["FUID"].ToString();
//parFuId = dr["FUID"].ToString();
GerFolderAndFile(folderDt, childFuId, type, empID);

}
else
{
dr["FUID"] = row["FUID"];
dr["ParFUID"] = row["ParFUID"];
dr["FileName"] = row["FileName"];
dr["FileSize"] = row["FileSize"];
dr["FileType"] = row["FileType"];
dr["OwnerID"] = row["OwnerID"];
dr["FileSavePath"] = row["FileSavePath"];
dr["FileSaveName"] = row["FileSaveName"];
dr["FileTypeName"] = row["FileTypeName"];
dr["KeyInID"] = row["KeyInID"];
dr["DirType"] = row["DirType"];
}
folderDt.Rows.Add(dr);
}
return folderDt;
}
#endregion

 

一般处理程序FolderUploader.ashx(用于导入)filePath就是FolderUploader.ashx 注意:如果你要上传到服务器端一定要绝对路径例如:http://192.×.××.××:××××/FolderUploader.ashx
ActiveX 方法

public string OpenFolderdialog(string filePath)

{

  ……………………

  System.Net.WebClient webclient = new System.Net.WebClient();
  webclient.UploadFile(filePath, "POST", fileuri);

  ………………

}

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Configuration;
using FumaCRM_BS.BLL;
using System.Web.SessionState;

namespace CRM_BS.WebUI
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class FolderUploader : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
//导入
if (!string.IsNullOrEmpty(context.Request.QueryString["type"]))
{
string keyId = "admin";
foreach (string fileKey in context.Request.Files)
{
string time = DateTime.Now.ToShortDateString();
string path = string.Empty;
if (context.Request.QueryString["type"] == "1")
path = context.Server.MapPath(ConfigurationManager.AppSettings["FileUploadPathCompanyDoc"]);
else
path = context.Server.MapPath(ConfigurationManager.AppSettings["FileUploadPathPrivateDoc"]);
if (!Directory.Exists(path))//判断服务器上传路径是否存在
Directory.CreateDirectory(path);
path += time + @"\";
if (!Directory.Exists(path))//判断存储路径日期格式路径是否存在
Directory.CreateDirectory(path);
FileManager _fileManager = new FileManager();
string fileSaveName = _fileManager.GetFileSaveName();
HttpPostedFile file = context.Request.Files[fileKey];
string extension = System.IO.Path.GetExtension(file.FileName).ToLower();
file.SaveAs(Path.Combine(path, keyId + file.FileName)); //fileSaveName + extension
}
}
}

public bool IsReusable
{
get
{
return false;
}
}
}
}

webconfig

     <add key="WebSiteAddress" value="http://192.×.×.12:×××/FolderUploader.ashx"/>
<add key="ServicePath" value="http://192.×.×.12:×××"/>
<add key="FileUploadPath" value="~/DocManage/"/><!--上传文件根目录-->
<add key="FileUploadPathCompanyDoc" value="DocManage/CompanyDoc/"/> <!--上传文件根目录:公司-->
<add key="FileUploadPathPrivateDoc" value="DocManage/PrivateDoc/"/><!--上传文件根目录:个人-->

 

http://192.×.×.12:××× 文件夹需要上传的服务器端地址

 

 效果:

 

BS文件夹上传操作(二) ——基本功能实现》功能是实现了,但是部署到服务器端,出现了问题。上传,下载 选择的是客户端,但是后台执行时默认的选择了服务器端。另外安全性不是很好。需要对浏览器进行安全设置。

 

如果你的需求中也是这样,希望这篇可以给你带来帮助……

 

 

 







 



作者:PEPE
出处:http://pepe.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

posted @ 2012-03-07 09:16  PEPE YU  阅读(3838)  评论(20编辑  收藏  举报