由于WebClient的uploadData不对数据进行编码,因此向其添加“Content-Type”,“multipart / form-data”标头会产生什么影响?

C#的uploadData方法不对正在发送的数据进行编码。 因此,如果我使用此方法发送文件(在将其转换为字节后),并且接收方正在寻找multiform/form-datapost,那么它显然不起作用。 将添加如下标题:

 WebClient c = new WebClient(); c.Headers.Add("Content-Type", "multipart/form-data"); 

让它发送加密为多种forms的数据,或者数据是否仍然没有加密(因此服务器需要多种数据无法解析)?

请注意,我无法使用WebClient's uploadFile ,因为我没有权限在客户端获取文件路径位置(我只有一个流,我可以转换为字节)

如果您希望它安全,为什么不使用WebClient的UploadFile而不是https? 这将自动处理添加multipart/form-data

使用UploadFile示例

http://msdn.microsoft.com/en-us/library/36s52zhs.aspx

还有一件事,编码和加密是两件不同的事情。

编辑:

如果您在WebClient项目中使用WebClient,则应该将问题标记为Silverlight。 无论如何,SL中的WebClient类没有任何UploadData方法。 有关详细信息,请参阅此

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.95%29.aspx

无论如何,这是你的问题的工作解决方案:

在您点击按钮时,请输入以下代码:

 OpenFileDialog dialog = new OpenFileDialog(); bool? retVal = dialog.ShowDialog(); if (retVal.HasValue && retVal == true) { using (Stream stream = dialog.File.OpenRead()) { MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); WebClient webClient = new WebClient(); webClient.Headers["Content-type"] = "multipart/form-data; boundary=---------------------------" + _boundaryNo; webClient.OpenWriteAsync(new Uri("http://localhost:1463/Home/File", UriKind.Absolute), "POST", new { Stream = memoryStream, FileName = dialog.File.Name }); webClient.OpenWriteCompleted += new OpenWriteCompletedEventHandler(webClient_OpenWriteCompleted); } } 

和事件本身:

 void webClient_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e) { if (e.Error == null) { Stream responseStream = e.Result as Stream; dynamic obj = e.UserState; MemoryStream memoryStream = obj.Stream as MemoryStream; string fileName = obj.FileName; if (responseStream != null && memoryStream != null) { string headerTemplate = string.Format("-----------------------------{0}\r\n", _boundaryNo); memoryStream.Position = 0; byte[] byteArr = memoryStream.ToArray(); string data = headerTemplate + string.Format("Content-Disposition: form-data; name=\"pic\"; filename=\"{0}\"\r\nContent-Type: application/octet-stream\r\n\r\n", fileName); byte[] header = Encoding.UTF8.GetBytes(data); responseStream.Write(header, 0, header.Length); responseStream.Write(byteArr, 0, byteArr.Length); header = Encoding.UTF8.GetBytes("\r\n"); responseStream.Write(byteArr, 0, byteArr.Length); byte[] trailer = System.Text.Encoding.UTF8.GetBytes(string.Format("-----------------------------{0}--\r\n", _boundaryNo)); responseStream.Write(trailer, 0, trailer.Length); } memoryStream.Close(); responseStream.Close(); } } 

其中_boundaryNo是private string _boundaryNo = DateTime.Now.Ticks.ToString("x");

我使用过Asp.Net MVC 4和Silverlight 5。

祝好运 :)