首先,在你的VisualC#webproject中增加一个上传用的WebForm,为了要上传文件,需要在ToolBox中选择HTML类的FileField控件,将此控件加入到WebForm中,然而此时该控件还不是服务端控件,我们需要为它加上如下一段代码:<inputid=uploadfile1type=filesize=49runat=server>,这样它就成为服务端控件了,如果需要同时上传数个文件时,我们可以相应增加此控件。
需要注意的是代码中一定要把<form>的属性设置成为:
/// <summary>/// 上传
/// </summary>
/// <param name="filename">要上传的本地文件名</param>
public void Upload(string filename)
{
FileInfo fileInf = new FileInfo(filename)
string uri = ftpURI + fileInf.Name
FtpWebRequest reqFTP
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri))
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword)
reqFTP.KeepAlive = false
reqFTP.Proxy = null
reqFTP.Method = WebRequestMethods.Ftp.UploadFile
reqFTP.UseBinary = true
reqFTP.ContentLength = fileInf.Length
int buffLength = 2048
byte[] buff = new byte[buffLength]
int contentLen
FileStream fs = fileInf.OpenRead()
try
{
Stream strm = reqFTP.GetRequestStream()
contentLen = fs.Read(buff, 0, buffLength)
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen)
contentLen = fs.Read(buff, 0, buffLength)
}
strm.Close()
fs.Close()
}
catch (Exception ex)
{
Error_Log("FTP上传文件时发成错误,详细错误参数请查看错误日志。", "Upload Error --> " + ex.Message + "\r\n" + ex.StackTrace)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)