Image upload using Webservice C#

Asked

Viewed 627 times

2

I would like a help to know what is the best way to upload an image using webservice c#, I have tried several forms and several examples but could not.

I tried to convert an image to string Base64, I was not successful. The way for communication between the webservice I used the library KSOAP2, I also tried JSON, HTTP POST... Some run but do not send photo 640 x 480.

Thanks in advance.

  • 1

    Hello @Whallas and welcome to [pt.so]. I recommend a visit to [help] and a reading on [Ask]. Reinforce your question with an example of code you’ve done, or something for other Ops to help you with what you’ve already done.

1 answer

1

To upload a photo, you can use the Webinvoke annotation, which allows you to create WCF endpoints in REST format. Follow the code passage to the explanatory:

[WebInvoke(UriTemplate = "UploadPhoto/{fileName}/{description}", Method = "POST")] 
public void UploadPhoto(string fileName, string description, Stream fileContents) 
{ 
    byte[] buffer = new byte[32768]; 
    MemoryStream ms = new MemoryStream(); 
    int bytesRead, totalBytesRead = 0; 
    do 
    { 
        bytesRead = fileContents.Read(buffer, 0, buffer.Length); 
        totalBytesRead += bytesRead; 

        ms.Write(buffer, 0, bytesRead); 
    } while (bytesRead > 0); 

    // Save the photo on database. 
    using (DataAcess data = new DataAcess()) 
    { 
        var photo = new Photo() { Name = fileName, Description = description, Data = ms.ToArray(), DateTime = DateTime.UtcNow }; 
        data.InsertPhoto(photo); 
    } 

    ms.Close(); 
    Console.WriteLine("Uploaded file {0} with {1} bytes", fileName, totalBytesRead); 
} 

This excerpt comes from a complete example with Client and Server for image upload MSDN.

Perhaps a similar implementation with WEB API is more comfortable. See more details on WEB API on the Asp.net website.

If you implement the webservice (WCF or WEB API) using REST, it will be easier to send data regardless of the source language

  • He’s not using C#, but Java - equal contexts, different environments. Also, responses with only links are not pleasant - that’s why I negatively. Read more here.

  • Okay, I’ll fix it.

  • Maia did not specify that the client is an android application. In android also works your example? How would I send the Stream fileContents.

  • Yes, if you are using a REST webservice, you can send a post of any language/platform. I found a way to implement a post using android SDK here, maybe it’ll help you.

  • Thanks Maia, I’ll try here now.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.