web上传文件夹到服务器上,WebClient上传文件至服务器

在项目中用到了将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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值