首页 新闻 会员 周边

用C#实现图片上传并保存相对路径

0
悬赏园豆:5 [已解决问题] 解决于 2016-10-24 10:02

客户端上传图片发至服务器指定文件夹
并获得保存至服务器数据库的相对路径

人本薄凉的主页 人本薄凉 | 初学一级 | 园豆:9
提问于:2016-10-22 16:59
< >
分享
最佳答案
0

#region 上传照片及其路径
string ImgPath;
string imgFile;
private void btnPicTure_Click(object sender, EventArgs e)
{
//打开文件
OpenFileDialog openFileDialog = new OpenFileDialog();
//获取或设置当前文件名筛选器字符串,该字符串决定对话框的"另存为文件类型"或"文件类型"框中出现的选择内容
openFileDialog.Filter = "Files|*.jpg;*.jpeg;*.png;*.gif";
//获取文件对话框中的初始目录(图片路径)
openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//获取图片路径
ImgPath = openFileDialog.FileName;
//显示图片、修改图片大小
picPicture.Image = Image.FromFile(ImgPath).GetThumbnailImage(117, 143, null, IntPtr.Zero);
//从图片截取要上传图片的名称到数据库保存方便查询
imgFile = "/IDcard/"+ImgPath.Remove(0, ImgPath.ToString().LastIndexOf(@""));
//数据库:IDcard/143943572260.jpg
}
}

#endregion

#region 上传图片到服务器
public void Uploading(string ImgPathFileName)
{
//OpenFileDialog myOpenFileDialog = new OpenFileDialog();
//myOpenFileDialog.ShowDialog();
//string WebName = myOpenFileDialog.FileName;
//定义_webClient对象
WebClient _webClient = new WebClient();
//使用Windows登录方式
_webClient.Credentials = new NetworkCredential("test", "W12345678w");
//上传的链接地址(文件服务器)
Uri _uri = new Uri(@"http://192.168.1.252:8010/IDcard" + ImgPathFileName.Remove(0, ImgPathFileName.ToString().LastIndexOf(@"\")));
//要传到指定文件夹则URL为:@"http://192.168.1.252:8010//指定文件夹名称"+"文件名"
//注册上传进度事件通知
_webClient.UploadProgressChanged += _webClient_UploadProgressChanged;
//注册上传完成事件通知
_webClient.UploadFileCompleted += _webClient_UploadFileCompleted;
//异步从D盘上传文件到服务器
_webClient.UploadFileAsync(_uri, "PUT", ImgPathFileName);
}

//下载完成事件处理程序
private static void _webClient_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
MessageBox.Show("上传成功...");
}

//下载进度事件处理程序
private static void _webClient_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
MessageBox.Show($"{e.ProgressPercentage}:{e.BytesSent}/{e.TotalBytesToSend}");
}
#endregion

人本薄凉 | 初学一级 |园豆:9 | 2016-10-24 10:01
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册