I’m in a need to send a HttpPostedFileBase to a wcf serivce for processing which runs at the server, from the front end of web page after user click “upload a file” button. I used HttpPostedFileBase in the service contract first, but it didn’t work. Then I tried to put HttpPostedFileBase into the data contract but it still didn’t work. I struggled two days to go through that problem. Now here is the approach:
In Service Contract:
[ServiceContract]
public interface IFileImportWcf
{
[OperationContract]
string FileImport(byte[] file);
}
And found these two methods to convert byte[] to stream and vice versa.
public byte[] StreamToBytes(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
stream.Seek(0, SeekOrigin.Begin);
return bytes;
}
public Stream BytesToStream(byte[] bytes)
{
Stream stream = new MemoryStream(bytes);
return stream;
}
In the controller:
[HttpPost]
public ActionResult Import(HttpPostedFileBase attachment)
{
//convert HttpPostedFileBase to bytes[]
var binReader = new BinaryReader(attachment.InputStream);
var file = binReader.ReadBytes(attachment.ContentLength);
//call wcf service
var wcfClient = new ImportFileWcfClient();
wcfClient.FileImport(file);
}
My question is: What’s the better way to send a HttpPostedFileBase to a wcf service?
You need to use WCF Data Streaming here.
As I understood from your question you have control over your WCF Service contract.
If you change contract to something like the following:
Then you will be able to use it on client side:
Please note that you need to enable streaming in configuration
(see link above for more details)