直接上代码和效果图,有问题欢迎提问共同交流学习,创作不易点个赞呗。
/// <summary>
/// 上传功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Title = "上传资料";
openFile.Filter = "|*.*||*.png||*.jpg||*.bmp";
openFile.Multiselect = false;
openFile.RestoreDirectory = true;DialogResult dialogResult = openFile.ShowDialog();
if (dialogResult == DialogResult.OK)
{
bool state = ServerConnectState(@"\\192.168.16.43", "admin", "1234");
if (state == true)
{
string fileName = openFile.FileName;
FileInfo file = new FileInfo(fileName);
if (file.Extension == ".png" || file.Extension == ".jpg" || file.Extension == ".bmp") //检查格式
{
if (file.Length > 0)
{
if (file.Length < 5 * 1024 * 1024)
{
string NewFileName = DateTime.Now.ToString("yyyyMMddHHms") + fileName.Substring(fileName.LastIndexOf("."));
WebClient myWebClient = new WebClient();
myWebClient.UploadFile(@"F:\Images\" + NewFileName, "POST", fileName);
MessageBox.Show("已上传。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("上传图片不能大于5M。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("无效图片", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
else
{
MessageBox.Show("仅支持图片格式:“png/.jpg/.bmp”。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}}
else
{
MessageBox.Show("服务器共享目录连接失败,账号或密码错误,凭证无效。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
这段是服务器连接验证代码/需要服务器验证就加上这段
/// <summary>
/// 服务器连接状态
/// </summary>
/// <param name="path">服务器文件夹地址:\\192.168.16.43\image</param>
/// <param name="user">账号</param>
/// <param name="pwd">密码</param>
/// <returns>true/fales</returns>
private static bool ServerConnectState(string path, string user, string pwd)
{
Process proc = new Process();
try
{
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true; //创建无窗口
proc.Start();
string dos = "net use " + path + " " + pwd + " /user:" + user;
proc.StandardInput.WriteLine(dos);
proc.StandardInput.WriteLine("exit");
while (proc.HasExited == false)
{
proc.WaitForExit(1000);
}
string errormsg = proc.StandardError.ReadToEnd();
proc.StandardError.Close();
if (string.IsNullOrEmpty(errormsg))
{
return true;
}
else
{
return false;
}
}
catch (Exception)
{
return false;
}
finally
{
proc.Close();
proc.Dispose();
}
}
注意:报错提示 Access to the path 'F:\image' is denied.”错误 翻译:拒绝访问路径“F:\image”。“
解决方法:我的原因是没有给上传文件命名导致的提示这个错误。同时排查共享文件夹权限。