原文 利用WebClient上传参数及文件流到远程ashx服务
1 思路:
WebClient.UploadFile()方法可以上传文件;UploadData()方法可以上传数据参数;如何合二为一既上传文件又上传参数呢?可将文件也当做参数,调用UploadData()方法
2 客户端
|
1 FileStream fs = new FileStream(“需上传文文件路径”, FileMode.Open, FileAccess.Read); 2 3 byte[] byteFile = new byte[fs.Length]; 4 5 fs.Read(byteFile, 0, Convert.ToInt32(fs.Length)); 6 7 fs.Close(); 8 9 string postData = "param1=pwd&FileName=file1.xml&UploadFile=" + HttpUtility.UrlEncode(Convert.ToBase64String(byteFile)); 10 11 var webclient = new WebClient(); 12 13 webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); 14 15 byte[] byteArray = Encoding.UTF8.GetBytes(postData); 16 17 byte[] buffer = webclient.UploadData(“远程ashx URL”, "POST", byteArray); 18 19 var msg = Encoding.UTF8.GetString(buffer);
3 服务端
1 string param1= context.Request["param1"].ToString(); 2 FileStream fs = new FileStream(“需要保存文件的路径”, FileMode.Create, FileAccess.Write); 3 fs.Write(Convert.FromBase64String(context.Request["UploadFile"].ToString()), 0, Convert.FromBase64String(context.Request["UploadFile"].ToString()).Length); 4 fs.Flush(); 5 fs.Close();