上篇《BS文件夾上傳操作 》大概說明了我所需要的需求,
接着上次的命題:
“如果有一個需求,要求你在BS上實現文件夾上傳操作功能?你該如何實現?”
ActiveX?Js插件?自定義控件 還是……
再看下需求:
客戶端選擇任一文件夾上傳到服務器中,在服務器上建立相關文件夾且相應文件上傳到相應的文件夾中。

操作:選擇任意一個文件夾上傳 文件夾中相關文件也上傳

出來的效果:

主要源碼:
/// <summary>
/// 導入->確定 方法
/// </summary>
/// <param name="path"></param>
[DirectMethod]
public void GetPath(string readPath)
{
string storePath = @"C:\Documents and Settings\Administrator\桌面\Test\"; //目標目錄
string strFile = FolderHelper.FindFileByPath(readPath, storePath);
CommonMethod.Show("", strFile, Ext.Net.MessageBox.Icon.INFO);
}
FolderHelper
/// <summary>
/// 根據路徑獲取該文件夾下文件
/// </summary>
/// <param name="readPath">文件讀取路徑</param>
/// <param name="storePath">文件存儲路徑</param>
/// <returns>導入成功,失敗</returns>
public static string FindFileByPath(string readPath, string storePath)
{
try
{
DirectoryInfo diInfo = new DirectoryInfo(readPath); //上傳
DirectoryInfo diInfoStore = new DirectoryInfo(storePath + diInfo.Name);//存儲
if (!diInfoStore.Exists)//存儲到指定路徑判斷文件夾不存在則新建
diInfoStore.Create();
FileSystemInfo[] fsInfo = diInfo.GetFileSystemInfos();//獲取該目錄下所有文件和子目錄
foreach (FileSystemInfo fs in fsInfo)//遍歷數組
{
if (fs is FileInfo)//文件
{
byte[] file = FileToBinary(fs.FullName);
BinaryToFile(storePath + diInfo.Name, fs.Name, file);
}
if (fs is DirectoryInfo)//文件夾
{
FindFileByPath(fs.FullName, storePath + diInfo.Name + "\\");
}
}
return "導入成功";
}
catch (Exception)
{
return "導入失敗";
}
}
/// <summary>
/// 將文件轉換為二進制流進行讀取
/// </summary>
/// <param name="fileName">文件完整名路徑</param>
/// <returns>文件二進制流</returns>
private static 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();
}
}
/// <summary>
/// 將二進制流轉換為對應的文件進行存儲
/// </summary>
/// <param name="storePath">存儲文件名的路徑</param>
/// <param name="fileName">文件名</param>
/// <param name="btBinary">二進制流</param>
private static void BinaryToFile(string storePath, string fileName, byte[] binary)
{
FileStream fsWrite = new FileStream(storePath + "\\" + fileName, FileMode.Create, FileAccess.Write);
try
{
if (fsWrite.CanWrite)
{
fsWrite.Write(binary, 0, binary.Length);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
fsWrite.Close();
}
}
基本的上傳功能實現,但是犧牲了安全性,抽空試試Left join.G 提供的幫助ActiveX。在這也感謝園中兩位朋友的Left join.G和sunriseyuen。
謝謝

作者:PEPE
出處:http://pepe.cnblogs.com/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
