在項目中用到了將WebClient上傳文件到服務(wù)器,經(jīng)在網(wǎng)上查找,自己添加到項目中進(jìn)行實(shí)驗了一番了,特將此代碼拷貝上來(lái):
/// <summary>
/// WebClient上傳文件至服務(wù)器
/// </summary>
/// <param name="localFilePath">文件名,全路徑格式</param>
/// <param name="serverFolder">服務(wù)器文件夾</param>
/// <returns></returns>
public static bool Upload(string localFilePath, string serverFolder, string newFileName)
{
//獲取服務(wù)器的IP
string ip = PublicMethod.GetIp();
if (!serverFolder.EndsWith("/") && !serverFolder.EndsWith(@"\"))
{
serverFolder = serverFolder + "/";
}
string uriString = "http://" + ip + "/" + serverFolder + newFileName;
/// 創(chuàng )建WebClient實(shí)例
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("您上傳的附件不能超過(guò) " + 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("文件目前不可寫(xiě)!");
}
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;
}
/// <summary>
/// 獲取服務(wù)器的IP
/// </summary>
/// <returns></returns>
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;
}