.NET两种常见上传下载文件方法

时间:2023-03-08 18:41:30

1.FTP模式

代码如下:

.NET两种常见上传下载文件方法

(1)浏览

       /// <summary>
/// 浏览文件
/// </summary>
/// <param name="tbControl">控件名称</param>
private void ViewFile(TextBox tbControl)
{
OpenFileDialog openFileDialogTemp = new OpenFileDialog();//提示用户打开文件弹窗 //设置文件类型
string filterStr = "";//文件类型过滤
int fileLength = * * ;//文件大小限制(1M = 1024KB = 1024*1024字节)
string fileLenDes = "100M";//文件大小描述,默认100M
switch (tbControl.Name)//根据控件名称判断过滤字符串
{
case "txtTemplatePath"://模板
filterStr = "All files(*.*)|*.*";
break;
case "txtCusSoftwarePath"://定制软件
filterStr = "All files(*.*)|*.*";
break;
default://检查清单
filterStr = "Word或Excel文件(*.doc,*.docx,*.xls,*.xlsx,*.wps,*.et)|*.doc;*.docx;*.xls;*.xlsx;*.wps;*.et;";
break;
}
openFileDialogTemp.Filter = filterStr; DialogResult dr = openFileDialogTemp.ShowDialog();//弹窗返回值
if (dr == DialogResult.OK)
{
//获取用户选择的文件
FileInfo fileInfo = new FileInfo(openFileDialogTemp.FileName);
if (fileInfo.Length > fileLength)//判断文件大小是否超出限制
{
this.MessageShow("上传文件不能大于" + fileLenDes);
return;
} tbControl.Text = openFileDialogTemp.FileName;
}
}

(2)上传

        // 定制软件上传
private void btnCusSoftwareUpload_Click(object sender, EventArgs e)
{
if (txtStatus.Text.Trim() != "实施中")
{
this.MessageShow("该任务不在实施中,不能进行此操作,请确认");
return;
} bool result = UpLoadFile(txtCusSoftwarePath);//代码在下面
if (result == true)
{
txtCusSoftwareName.Text = Path.GetFileName(txtCusSoftwarePath.Text);//更新定制软件名称
}
}
        /// <summary>
/// 上传文件
/// </summary>
/// <param name="tbControl">控件名称</param>
/// <returns>是否上传成功</returns>
private bool UpLoadFile(TextBox tbControl)
{
bool resFlag = false;
try
{
this.Cursor = Cursors.WaitCursor;//光标等待 string filePath = tbControl.Text.Trim();//文件路径
if (string.IsNullOrEmpty(filePath))
{
MessageShow("没有可上传的文件");
return resFlag;
} ////判断远程服务器中是否存在该文件(由于删除动作并没有删除服务器中的文件,所以如果某文件上传后被删除再上传就会出现无法上传的情况)
//if (FileIsExist(mFtpFullPath + Path.GetFileName(filePath)) == true)
//{
// this.MessageShow("远程服务器中已经存在该文件,请勿重复上传!");
// return resFlag;
//} Upload(filePath, mFtpFullPath, mFtpUserId, mFtpPassword);//代码在下面 //保存文件
//说明:BARCODE.PDM_PACK_IMAGES表是存上传文件的表,其中PD_ID字段是对应需要上传的表的主键,IMAGES字段是文件上传到ftp的完全路径
int saveRecordID = SaveUploadFile(filePath);//保存在本地表的主键id
mSavePathID = saveRecordID;
int tIndex;//临时变量,用来区分保存类型
if (saveRecordID > )//保存文件成功
{
//本地表中保存上传文件的ftp表记录ID
Hashtable ht = new Hashtable();
string FileName = Path.GetFileName(filePath);//文件名称
switch (tbControl.Name)//文件保存路径(存的是保存表的记录id)
{
case "txtCusSoftwarePath"://定制软件上传
ht.Add("CusSoftwarePath", saveRecordID.ToString());
ht.Add("CusSoftwareName", FileName); mChoosedLabelRow["CUS_SOFTWARE_PATH"] = saveRecordID.ToString();//更新内存中的模板地址
tIndex = ;
break;
default://检查清单上传
ht.Add("CheckListPath", saveRecordID.ToString());
ht.Add("CheckListName", FileName); mChoosedLabelRow["CHECK_LIST_PATH"] = saveRecordID.ToString();//更新内存中的模板地址
tIndex = ;
break;
} int result = UpdateDatas(ht);//执行更新
if (result > )
{
resFlag = true;
switch (tIndex) //更新临时变量中的模板地址
{
case :
mTemplatePath = GetFileSavePath(tIndex, mLableID, saveRecordID.ToString());
break;
case :
mCustomSoftwarePath = GetFileSavePath(tIndex, mLableID, saveRecordID.ToString());
break;
default:
mCheckListPath = GetFileSavePath(tIndex, mLableID, saveRecordID.ToString());
break;
}
} }//if (saveRecordID > 0) end
}//try end
catch (Exception ex)
{
ErrorCommand(ex);
}
finally
{
this.Cursor = Cursors.Default;
}
return resFlag;
}
        /// <summary>
/// ftp上传
/// </summary>
/// <param name="fileName">客户端上传文件名称</param>
/// <param name="ftpFullPath">ftp完整路径,例如 ftp://10.18.178.154/mes_upload/ManuNotice/P108A5/126708201002/label/ </param>
/// <param name="ftpUserId">ftp登陆用户名</param>
/// <param name="ftpPassword">ftp登陆密码</param>
public static void Upload(string fileName, string ftpFullPath, string ftpUserId, string ftpPassword)
{
FileInfo fileInf = new FileInfo(fileName);//--using System.IO;
string uri = ftpFullPath + fileInf.Name;
FtpWebRequest reqFTP;//--using System.Net; // 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));//fileInf.Name //ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserId, ftpPassword); //默认为True,连接不会被关闭
//在一个命令之后执行
reqFTP.KeepAlive = false; // 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // 指定数据传输类型
reqFTP.UseBinary = true; // 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length; // 缓冲大小设置为2kb
int buffLength = ; byte[] buff = new byte[buffLength];
int contentLen; // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream(); // 每次读文件流的2kb
contentLen = fs.Read(buff, , buffLength); // 流内容没有结束
while (contentLen != )
{
// 把内容从file stream 写入 upload stream
strm.Write(buff, , contentLen); contentLen = fs.Read(buff, , buffLength);
} // 关闭两个流
strm.Close(); }
catch (Exception)
{ }
finally
{
fs.Close();
} }//function end

注意,上传下载地址可以放在配置文件中取,例如:

.NET两种常见上传下载文件方法

后台取数据:

 ms.Url = System.Configuration.ConfigurationSettings.AppSettings["GetAccessoryPathForMes"].ToString();//ftp地址WebService
ftpUserId = System.Configuration.ConfigurationSettings.AppSettings["FtpUserId"].ToString(); //ftp登陆账号
ftpPassword = System.Configuration.ConfigurationSettings.AppSettings["FtpPassword"].ToString(); //ftp登陆密码
 


(3)下载

        /// <summary>
/// 下载文件
/// </summary>
/// <param name="tbControl">控件名称</param>
private void DownLoadFile(TextBox tbControl)
{
try
{
this.Cursor = Cursors.WaitCursor; string localFilePath = String.Empty;
SaveFileDialog saveFileDialog = new SaveFileDialog(); //设置文件相关信息
string filterStr = "";//过滤文件类型字符串
string filePathStr = "";//路径
switch (tbControl.Name)//根据控件名称判断过滤字符串
{
case "txtTemplatePath":
filterStr = "All files(*.*)|*.*";
filePathStr = mTemplatePath;
break;
case "txtCusSoftwarePath":
filterStr = "All files(*.*)|*.*";
filePathStr = mCustomSoftwarePath;
break;
default:
filterStr = "Word或Excel文件|*.doc;*.docx;*.xls;*.xlsx;*.wps;*.et;";
filePathStr = mCheckListPath;
break;
}
saveFileDialog.Filter = filterStr; //设置文件名称:
string filePath = filePathStr; //下载的文件名称为空时return
if (string.IsNullOrEmpty(filePath))
{
this.MessageShow("找不到当前文件存储路径");
return;
}
string fileName = Path.GetFileName(filePath);//获取文件名和扩展名
saveFileDialog.FileName = fileName; //设置默认文件类型显示顺序
saveFileDialog.FilterIndex = ; //保存对话框是否记忆上次打开的目录
saveFileDialog.RestoreDirectory = true; //点了保存按钮进入
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
//获得文件路径
localFilePath = saveFileDialog.FileName.ToString(); PublicMethod.Download(localFilePath, filePath, mFtpUserId, mFtpPassword);
}
}
catch (Exception ex)
{
ErrorCommand(ex);//异常处理
}
finally
{
this.Cursor = Cursors.Default;
}
} /// <summary>
/// ftp下载
/// </summary>
/// <param name="clientFilePath">下载保存的客户端完整路径</param>
/// <param name="fullPath">ftp完整文件路径及文件名</param>
/// <param name="ftpUserId">ftp登陆用户</param>
/// <param name="ftpPassword">ftp登陆密码</param>
public static void Download(string clientFilePath, string fullPath, string ftpUserId, string ftpPassword)
{
string dFileName = Path.GetFileName(fullPath); string rootPath = fullPath.Substring(, fullPath.LastIndexOf("/")) + "/"; //定义FTP请求对象
FtpWebRequest reqFTP = null;
//定义FTP响应对象
FtpWebResponse response = null;
//存储流
FileStream outputStream = null;
//FTP数据流
Stream ftpStream = null; try
{
//生成下载文件
outputStream = new FileStream(clientFilePath, FileMode.Create); //生成FTP请求对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(rootPath + dFileName)); //设置登录FTP帐号和密码
reqFTP.Credentials = new NetworkCredential(ftpUserId, ftpPassword); //默认为True,连接不会被关闭
//在一个命令之后执行
reqFTP.KeepAlive = false; //设置下载文件方法
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; //设置文件传输类型
reqFTP.UseBinary = true; //生成FTP响应对象
response = (FtpWebResponse)reqFTP.GetResponse(); //获取FTP响应流对象
ftpStream = response.GetResponseStream(); //响应数据长度
long cl = response.ContentLength; int bufferSize = ; int readCount; byte[] buffer = new byte[bufferSize]; //接收FTP文件流
readCount = ftpStream.Read(buffer, , bufferSize); while (readCount > )
{
outputStream.Write(buffer, , readCount); readCount = ftpStream.Read(buffer, , bufferSize);
}
}
catch (Exception)
{
//MessageShow(ex.ToString());
}
finally
{
if (ftpStream != null)
{
ftpStream.Close();
} if (outputStream != null)
{
outputStream.Close();
} if (response != null)
{
response.Close();
}
}
}

(由于时间关系很多细节没有处理,这只是工作中的一个摘抄,不详之处还请原谅。)

2.文件流模式

.NET两种常见上传下载文件方法

        /// <summary>
/// 来料设计稿/标贴设计稿下载
/// </summary>
/// <param name="btnID">0代表来料设计稿,1代表标贴设计稿</param>
private void DownLoadDesignDraft(int btnID)
{
try
{
this.Cursor = Cursors.WaitCursor;//设置光标等待 #region 获取下载文件所需相关信息 string webUrl = string.Empty;//下载地址
string[] tempArray = null;//临时数组(数据库中的来料设计稿ID和名称是放一起的,格式如“id|name”)
string backFileName = string.Empty;//如果文件名称不存在就临时创建一个名称
string onlyID = string.Empty;//下载接口对应的唯一id
string fileName = string.Empty;//下载文件的名称 if (btnID == )//来料设计稿
{
tempArray = mChoosedLabelRow["INCOMINGFILE"].ToString().Trim().Split('|');
//backFileName = "标贴类任务维护来料设计稿" + DateTime.Now.ToString("yyyyMMddhhmmssfff");
}
else //标贴设计稿
{
tempArray = mChoosedLabelRow["LABELFILE"].ToString().Trim().Split('|');
//backFileName = "标贴类任务维护标贴设计稿" + DateTime.Now.ToString("yyyyMMddhhmmssfff");
} if (tempArray != null && tempArray.Length > )
{
onlyID = tempArray[].ToString(); //下载接口对应的唯一id
fileName = tempArray[].ToString();//下载文件的名称 if (onlyID == "" || fileName == "")
{
this.MessageShow("下载文件ID或文件名称不存在,请确认");
return;
} //fileName = fileName.Replace(".xlsx", "").Replace(".xls", "") + ".xlsx";//添加文件后缀 // 从配置文件中取地址,地址例如:http://10.5.4.28/PDM_Eai/EaiService/ProdName/PDM_M00_AttachFileStreamSrv.aspx
webUrl = System.Configuration.ConfigurationSettings.AppSettings["LabelTypeTaskManage_DownloadAddress"].ToString();
if (webUrl == "")
{
this.MessageShow("找不到文件的下载地址");
return;
} }//if (tempArray != null && tempArray.Length > 1) end
else
{
this.MessageShow("没有可以下载的文件");
return;
} #endregion SaveFileDialog saveDialog = new SaveFileDialog();//保存文件对话框,--using System.Windows.Forms;
//saveDialog.Filter = "All files(*.xls,*.xlsx)|*.xls;*.xlsx";//设置文件类型
saveDialog.Filter = "All files|*.*";//设置文件类型
saveDialog.FileName = fileName;//设置文件名称
saveDialog.FilterIndex = ;//设置默认文件类型显示顺序
saveDialog.RestoreDirectory = true; //保存对话框是否记忆上次打开的目录
string localFilePath = String.Empty;//下载文件的本地保存地址 //点了保存按钮进入
if (saveDialog.ShowDialog() == DialogResult.OK)
{
//获得文件路径
localFilePath = saveDialog.FileName.ToString(); //开始下载
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(webUrl + "?id=" + onlyID);--using System.Net;
HttpWebResponse wr = (HttpWebResponse)req.GetResponse();--using System.Net;
Stream responseStream = wr.GetResponseStream();--using System.IO;
StreamReader reader = new StreamReader(responseStream);--using System.IO; FileStream fs = new FileStream(@"" + localFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
int iBufferSize = ;//响应长度
byte[] byteFileBlock = new byte[iBufferSize];
int bytesRead = ;
while (true)
{
bytesRead = responseStream.Read(byteFileBlock, , iBufferSize); if (bytesRead == )
{
break;
}
fs.Write(byteFileBlock, , bytesRead);
}
} }//try end
catch (Exception ex)
{
ErrorCommand(ex);
}
finally
{
this.Cursor = Cursors.Default;
} }//function end

相关文章