Dau*_*aud 5 c# http multipartform-data
C#的uploadData方法不对正在发送的数据进行编码.因此,如果我使用此方法发送文件(在将其转换为字节之后),并且接收方正在寻找multiform/form-data帖子,那么它显然将无效.将添加如下标题:
WebClient c = new WebClient();
c.Headers.Add("Content-Type", "multipart/form-data");
Run Code Online (Sandbox Code Playgroud)
让它发送加密为多种形式的数据,或者数据是否仍然没有加密(因此服务器需要多种数据无法解析)?
请注意,我无法使用WebClient's uploadFile,因为我没有权限在客户端获取文件路径位置(我只有一个流,我可以转换为字节)
UploadFile如果您希望WebClient安全,为什么不使用WebClient而不是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);
}
}
Run Code Online (Sandbox Code Playgroud)
和事件本身:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
_boundaryNo是哪里 private string _boundaryNo = DateTime.Now.Ticks.ToString("x");
我使用过Asp.Net MVC 4和Silverlight 5.
祝好运 :)
| 归档时间: |
|
| 查看次数: |
6287 次 |
| 最近记录: |