原理:在客户端先把上传的文件转换成 byty[] 再在服务端 进行保存到服务器本地。
服务端代码:
/// <summary>
///
/// </summary>
/// <param name="data">数据流</param>
/// <param name="folder">保存到服务器的本地服务下的指定“文件夹名称”</param>
/// <param name="fileName">上传的文件名(带后缀)</param>
/// <returns></returns>
public string UpLoadFile(byte[] data, string folder, string fileName)
{
string error = "";
System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
string url = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, folder);
string pathName = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, folder, fileName);
if(File.Exists(pathName))
{
error = "文件已存在";
return error;
}
//是否存在 当前文件夹,不存在就创建
if (!Directory.Exists(url))
{
Directory.CreateDirectory(url);
}
string paths = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, folder + @"\" + fileName);
System.IO.FileStream fs = System.IO.File.Open(paths, System.IO.FileMode.CreateNew);
fs.Write(data, 0, data.Length);
fs.Flush();
fs.Close();
return error;
}
客户端:
/// <summary>
/// 上传文件
/// </summary>
/// <param name="id">主键</param>
/// <param name="folder">文件夹</param>
/// <returns></returns>
public string Upload(int id, string folder)
{
string error = "";
OpenFileDialog openFile = new OpenFileDialog();
//仅仅显示:Excel文件类型
openFile.Filter = "(*.xls,*.xlsx,*.xlsm)|*.xls;*.xlsx;*.xlsm";
//不能文件多选
openFile.Multiselect = false;
//选择 Excel 文件
if (openFile.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
System.IO.Stream s = openFile.OpenFile();
byte[] data = new byte[s.Length];
s.Read(data, 0, data.Length);
s.Close();
error = _Select.UpLoadFile(data, folder, openFile.SafeFileName);
if(error == "")
{
//记录到数据库
var newRow = _FileRecordDs.FileRecord.NewFileRecordRow();
newRow.FolderID = id;
newRow.Name = Path.GetFileNameWithoutExtension(openFile.FileName);
newRow.Suffix = Path.GetExtension(openFile.FileName);
newRow.EndEdit();
_FileRecordDs.FileRecord.AddFileRecordRow(newRow);
Update();
}
}
else
{
openFile.Dispose();
return "取消导入。";
}
openFile.Dispose();
return error;
}