上传遍历文件夹的上传文件(本机测试)
using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
/// <summary>
///FileStreamUpload 的摘要说明
/// </summary>
public class FileStreamUpload
{
public FileStreamUpload()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public static string FileDirectoryUpload(string path)
{
string fileAndPath = "上传成功!";
try
{
DirectoryInfo info = new DirectoryInfo(path);
if (!info.Exists || info == null)
fileAndPath= "文件夹为空!";
FileSystemInfo[] files = info.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i] as FileInfo;
//是文件
if (file != null)
FileUpload(file.FullName);
//对于子目录,进行递归调用
else
FileDirectoryUpload(files[i].FullName);
}
return fileAndPath;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 根据路径,使用FileStream上传文件
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private static string FileUpload(string filePath)
{
string result = "";
string filename = "";
FileInfo file = new FileInfo(filePath);
string fileExtenName = file.Extension;
//string fileNewName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtenName;
int ipos = filePath.LastIndexOf("\\");
if (ipos.ToString() != "-1")
{
filename = filePath.Substring(ipos);
}
else
{
filename = filePath;
}
string aFirstName = filename.Substring(filename.LastIndexOf("\\") + 1, (filename.LastIndexOf(".") - filename.LastIndexOf("\\") - 1)) + file.Extension;
string fileSavePath = System.Web.HttpContext.Current.Server.MapPath(@"~\Upload\") + aFirstName;
///真正上传,从这里开始
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
//把文件流中转化成字节数组
byte[] imageBytes = new byte[(int)fs.Length];
fs.Read(imageBytes, 0, imageBytes.Length);
fs.Close();
MemoryStream ms = new MemoryStream(imageBytes);
//定义并实例化一个内存流,以存放提交上来的字节数组。
FileStream fss = new FileStream(fileSavePath, FileMode.Create);
ms.WriteTo(fss);
fss.Close();
ms.Close();
return result = "Upload/" + aFirstName;
}
}