使用wcf如何上传图片

时间:2012-06-19 10:44:52

标签: wcf

使用wcf / wcf网络服务上传图片给我举例?

在我的项目中,我想使用WCF上传图像

2 个答案:

答案 0 :(得分:2)

基本上你应该使用WCF streaming

[ServiceContract]
public interface ITransferService
{ 
    [OperationContract]
     void UploadFile(RemoteFileInfo request); 
}

public void UploadFile(RemoteFileInfo request)
{
    FileStream targetStream = null;
    Stream sourceStream =  request.FileByteStream;

    string uploadFolder = @"C:\\upload\\";

    string filePath = Path.Combine(uploadFolder, request.FileName);

    using (targetStream = new FileStream(filePath, FileMode.Create, 
                          FileAccess.Write, FileShare.None))
    {
        //read from the input stream in 65000 byte chunks

        const int bufferLen = 65000;
        byte[] buffer = new byte[bufferLen];
        int count = 0;
        while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
        {
            // save to output stream
            targetStream.Write(buffer, 0, count);
        }
        targetStream.Close();
        sourceStream.Close();
    }
}

答案 1 :(得分:0)

最简单的方法是在发送图像之前将图像转换为字节数组,然后将其转换回目标网站上的图像。

以下是两种方法:

public byte[] ImageToByteArray( Image image)
{
  var ms = new MemoryStream();
  image.Save(ms, ImageFormat.Png);
  return ms.ToArray();
}

public static Image ByteArrayToImage(byte[] byteArray)
{
  var ms = new MemoryStream(byteArray);
  return Image.FromStream(ms);
}

这意味着您的网络服务可以采用以下方法:

public void UploadImage( byte[] imageData )
{
  var image = ByteArrayToImage( imageData );
  //save image to disk here, or do whatever you like with it
}