POSTing image from Android to WCF Rest Service

2019-08-24 14:07发布

问题:

Hi Im using the following code: http://vikaskanani.wordpress.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/

To POST an image to a WCF Rest service. I do not know how do configure the WCF Rest Service, can you help? My current interface looks like this:

[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Bare,
           UriTemplate = "SaveImage",
           Method = "POST")]
void SaveImage();

Which does not work... might contain several errors?

回答1:

It's wrong. You should send Stream argument as a parameter for SaveImage method, and it's better to set TransferMode="StreamRequest" in your service web.config.

When POSTing image use binary/octet-stream content type and binary data in body of message. On server side - read it from stream.



回答2:

 using System.ServiceModel;
    using System.ServiceModel.Web;
    using System.IO;
    namespace RESTImageUpload { [ServiceContract] public interface IImageUpload { [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "FileUpload/{fileName}")] void FileUpload(string fileName, Stream fileStream); } }

using System.IO; 
namespace RESTImageUpload
{

public class ImageUploadService : IImageUpload
{

   public void FileUpload(string fileName, Stream fileStream)
    {

        FileStream fileToupload = new FileStream("D:\\FileUpload\\" + fileName, FileMode.Create);

        byte[] bytearray = new byte[10000];
        int bytesRead, totalBytesRead = 0;
        do
        {
            bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
            totalBytesRead += bytesRead;
        } while (bytesRead > 0);

        fileToupload.Write(bytearray, 0, bytearray.Length);
        fileToupload.Close();
        fileToupload.Dispose();

    }      

}
}