0
我有一個應用程序應該接收大文件,這就是爲什麼我使用stream
參數。通過WCF服務接收大文件
服務合同:
[ServiceContract]
public interface IFile
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/Upload?fileName={fileName}&requestType={requestType}", ResponseFormat = WebMessageFormat.Json)]
FileMetadata Upload(string fileName, RequestType requestType, Stream stream);
}
實現:
public FileMetadata Upload(string fileName, RequestType requestType, Stream stream)
{
var contract = GetContract(fileName, requestType, stream);
...
}
private static FileUploadRequest GetContract(string fileName, RequestType requestType, Stream content)
{
var ms = new MemoryStream();
content.CopyTo(ms);
return new FileUploadRequest
{
Filename = fileName,
RequestType = requestType,
Content = ms.ToArray()
};
}
但隨着流我收到的垃圾信息(邊界等),轉移XML的樣品是:
--a288ea6c-376a-4c7e-9680-39199e34082c
Content-Disposition: form-data
<Doc> ... rest of XML
如何轉讓流本身?我應該刪除客戶端邊界還是刪除服務器端邊界?因爲JS也應該使用這個服務,我不知道它是否包含這些附加信息或者不包含。
客戶端發送的請求是這樣的:
public async Task<FileMetadata> Upload(string fileName, RequestType requestType, Stream stream)
{
var requestUri = $"Upload?fileName={fileName}&requestType={requestType}";
using (var requestContent = new MultipartFormDataContent())
{
requestContent.Add(new StreamContent(stream));
var response = await _client.PostAsync(requestUri, requestContent).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return JsonConvert.DeserializeObject<FileMetadata>(responseContent);
}
}
throw new Exception();
}
它正常工作與HttpWebRequest
,但我想用更現代的apporach。我敢肯定,我做錯了什麼,請指教:
public FileMetadata Upload(string fileName, RequestType requestType, Stream stream)
{
var requestUri = $"Upload?fileName={fileName}&requestType={requestType}";
var request = WebRequest.CreateHttp(new Uri(_client.BaseAddress, requestUri));
request.Method = "POST";
request.AllowWriteStreamBuffering = false;
request.ContentLength = stream.Length;
using (var requestStream = request.GetRequestStream())
{
stream.CopyTo(requestStream);
}
using (var response = (HttpWebResponse) request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception();
}
using (var sr = new StreamReader(response.GetResponseStream()))
{
return JsonConvert.DeserializeObject<FileMetadata>(sr.ReadToEnd());
}
}
}