c winform 上传文件到mysql_WinForm上传文件至服务器
///
/// WebClient上傳文件至服務(wù)器
///
/// 文件名,全路徑格式
/// 服務(wù)器文件夾路徑
///
public bool Upload(string localFilePath, out string folderName,string newFileName)
{
//先創(chuàng)建文件夾
folderName = "";
try
{
Guid guid = Guid.NewGuid();
folderName = guid.ToString();
string diskPath = DAL.DataBaseOperator.GetValueFromApplictionConfig("diskPath");
if (!diskPath.EndsWith("/") && !diskPath.EndsWith(@"\"))
{
diskPath = diskPath + "/";
}
diskPath += folderName;
if (!Directory.Exists(diskPath))
{
//服務(wù)器創(chuàng)建文件夾
Directory.CreateDirectory(diskPath);
}
//再上傳數(shù)據(jù)
string serverFolder = DAL.DataBaseOperator.GetValueFromApplictionConfig("uploadPath");
if (!serverFolder.EndsWith("/") && !serverFolder.EndsWith(@"\"))
{
serverFolder = serverFolder + "/";
}
string uriString = serverFolder + folderName + "/" + newFileName;
/// 創(chuàng)建WebClient實(shí)例
WebClient myWebClient = new WebClient();
myWebClient.Credentials = CredentialCache.DefaultCredentials;
// 要上傳的文件
FileStream fs = new FileStream(newFileName, 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("文件目前不可寫!");
}
Application.DoEvents();
postStream.Close();
}
catch(Exception err)
{
//MessageBox.Show("文件上傳失敗,請(qǐng)稍候重試~");
DAL.Log.FileLogSys.FileLog.WriteLog(err.Message + err.StackTrace);
return false;
}
return true;
}
總結(jié)
以上是生活随笔為你收集整理的c winform 上传文件到mysql_WinForm上传文件至服务器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL高可靠_MySQL高可用与高可
- 下一篇: mysql docker自动化_dock