在项目中用到了将WebClient上传文件到服务器,经在网上查找,自己添加到项目中进行实验了一番了,特将此代码拷贝上来:
///
/// WebClient上传文件至服务器
///
/// 文件名,全路径格式
/// 服务器文件夹
///
public static bool Upload(string localFilePath, string serverFolder, string newFileName)
{
//获取服务器的IP
string ip = PublicMethod.GetIp();
if (!serverFolder.EndsWith("/") && !serverFolder.EndsWith(@"\"))
{
serverFolder = serverFolder + "/";
}
string uriString = "http://" + ip + "/" + serverFolder + newFileName;
/// 创建WebClient实例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上传的文件
FileStream fs = new FileStream(localFilePath, FileMode.Open, FileAccess.Read);
判断文件大小
//string strFileSize = DAL.DataBaseOperator.GetValueFromApplictionConfig("fileSize");
//int fileSize = Convert.ToInt32(strFileSize) * 1024 * 1024;
//if (fs.Length > fileSize)
//{
// MessageBox.Show("您上传的附件不能超过 " + strFileSize + "M");
// return false;
//}
BinaryReader r = new BinaryReader(fs);
//使用UploadFile方法可以用下面的格式
myWebClient.UploadFile(uriString, "PUT", localFilePath);
byte[] postArray = r.ReadBytes((int)fs.Length);
Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
if (postStream.CanWrite)
{
postStream.Write(postArray, 0, postArray.Length);
}
else
{
MessageBox.Show("文件目前不可写!");
}
System.Windows.Forms.Application.DoEvents();
postStream.Close();
}
catch (Exception err)
{
MessageBox.Show("文件上传失败,请稍候重试~");
//DAL.Log.FileLogSys.FileLog.WriteLog(err.Message + err.StackTrace);
return false;
}
return true;
}
///
/// 获取服务器的IP
///
///
public static string GetIp()
{
string Ip = "";
string strConn = DBUtil.SqlConnectionManager.ConnectionString();
int startIndex = strConn.IndexOf("=") + 1;
int endIndex = strConn.IndexOf(";");
int totalLength = strConn.Length;
int length = totalLength - startIndex - (totalLength - endIndex);
Ip = strConn.Substring(startIndex, length);
return Ip;
}