I need create WCF REST service for uploading large files. I made endpoint as streamed webHttpBinding, but it have not became streamed.
Service example:
[ServiceContract]
public interface IFiles
{
[OperationContract]
void UploadFile(Stream stream);
}
public class Files : IFiles
{
public void UploadFile(Stream stream)
{
const int BUFFER_SIZE = 64 * 1024;
byte[] buffer = new byte[BUFFER_SIZE];
using (TextWriter logWriter = new StreamWriter("d:\\UploadedFile.log"))
using (Stream fileStream = new FileStream("d:\\UploadedFile", System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
int readBytes = 0;
while (0 < (readBytes = stream.Read(buffer, 0, BUFFER_SIZE)))
{
fileStream.Write(buffer, 0, readBytes);
logWriter.WriteLine("{0}: {1} bytes saved", DateTime.Now, readBytes);
}
}
}
}
Web.config:
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebHttpBinding" maxBufferSize="65536" maxBufferPoolSize="524288"
maxReceivedMessageSize="1073741824" transferMode="Streamed" />
</webHttpBinding>
</bindings>
<services>
<service name="WcfService2.Files">
<endpoint behaviorConfiguration="WebHttpBehavior" binding="webHttpBinding"
bindingConfiguration="WebHttpBinding" name="Files" contract="WcfService2.IFiles" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="WebHttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="MyServiceBehavior">
<serviceMetadata />
<serviceDebug />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.web>
<httpRuntime maxRequestLength="500000" />
</system.web>
</configuration>
Client code:
using (Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlString);
request.Method = "POST";
request.ContentType = "application/octet-stream";
//request.ContentLength = fileStream.Length;
//request.AllowWriteStreamBuffering = false;
request.SendChunked = true;
Stream requestStream = request.GetRequestS开发者_如何转开发tream();
const int BUFFER_SIZE = 32 * 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int readBytes = 0;
while (0 < (readBytes = fileStream.Read(buffer, 0, BUFFER_SIZE)))
{
requestStream.Write(buffer, 0, readBytes);
Console.WriteLine("{0}: {1} bytes sent", DateTime.Now, readBytes);
System.Threading.Thread.Sleep(200);
}
requestStream.Close();
WebResponse response = request.GetResponse();
}
Code of method UploadFile is invoked only after requestStream.Close() is invoked. Why?
If you want to send it in parts you should add a flush in the while loop after the requestStream.Write()
requestStream.Flush();
This because streams may cache the output till it's nessecary to send it. See http://msdn.microsoft.com/en-us/library/system.io.stream.flush.aspx
精彩评论