[英]Specify content-type for files in multipart/form-data for Swagger
[英]Since WebClient's uploadData doesn't encode data, then what will be the effect of adding a “Content-Type”, “multipart/form-data” header to it
C#的uploadData方法不對正在發送的數據進行編碼。 因此,如果我使用此方法發送文件(將其轉換為字節后),並且接收方正在尋找multiform/form-data
帖子,那么它顯然不起作用。 將添加如下標題:
WebClient c = new WebClient();
c.Headers.Add("Content-Type", "multipart/form-data");
讓它發送加密為多種形式的數據,或者數據是否仍然沒有加密(因此服務器需要多種數據無法解析)?
請注意,我無法使用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。
祝好運 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.