WPF上传文件到服务器
Posted 该昵称有误
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF上传文件到服务器相关的知识,希望对你有一定的参考价值。
创建一个空网站,创建一个UploadFile.aspx项,
服务器报500错误时,请检查文件保存路径是否存在
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 foreach (string f in Request.Files.AllKeys) 4 { //在客户端传入新的文件 5 HttpPostedFile file = Request.Files[f]; 6 //在客户端传入一个新的文件名 7 string directory = Request.QueryString["d"]; 8 string filename = Request.QueryString["n"]; 9 //file.SaveAs(Server.MapPath("../ReportFile/" + filename + file.FileName.Substring(file.FileName.IndexOf(".")))); 10 string path = string.Format(@"G:\ReportFile\{0}\", directory); 11 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } 12 file.SaveAs(path + filename); 13 } 14 }
WPF中
1 using form = System.Windows.Forms; 2 private const string directory = "0123"; 3 public void Upload(string file) 4 { 5 FileInfo info = new FileInfo(file); 6 string url = string.Format("http://192.168.31.118:54040/UploadFile.aspx?d={0}&n={1}", directory, info.Name); 7 WebClient client = new WebClient(); 8 client.Credentials = CredentialCache.DefaultCredentials; //获取或设置发送到主机并用于请求进行身份验证的网络凭据 9 client.UploadFileAsync(new Uri(url), file); 10 client.UploadFileCompleted += new UploadFileCompletedEventHandler(result_UploadFileCompleted); 11 } 12 private void result_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e) 13 { 14 if (e.Error != null) 15 { 16 MessageBox.Show("上传失败:" + e.Error.Message); 17 } 18 else 19 { 20 MessageBox.Show("上传成功!"); 21 } 22 } 23 24 private void UploadFile_Click(object sender, RoutedEventArgs e) 25 { 26 form.OpenFileDialog _dialog = new form.OpenFileDialog(); 27 _dialog.Multiselect = true; 28 if (_dialog.ShowDialog() == form.DialogResult.OK) 29 { 30 string[] _files = _dialog.FileNames; 31 if (_files != null && _files.Length > 0) 32 { 33 foreach (var item in _files) 34 { 35 Upload(item); 36 } 37 } 38 } 39 }
以上是关于WPF上传文件到服务器的主要内容,如果未能解决你的问题,请参考以下文章