Uploading a Photo...

Topics: Web Api
Jul 13, 2011 at 9:24 PM

I'm hoping someone can help me.  I know it's something easy, but I'm missing it.  In preview 3 I was able to upload an image file to my WCF service with the code below (simplified).  After upgrading to Preview 4, this no longer works and always returns a 500.  It seems as if the correct method signature can't be found.  Any ideas?   The sample code is below.

Thanks,
David

[Description("Uploads a photo.")]
[WebInvoke(UriTemplate = "?name={fileName}", Method = HttpVerbs.PUT)]
public Photo UploadPhoto(Stream data, string fileName)
{
    Photo photo = PhotoUploadHandler.HandleUploadPhoto(fileName, data);
    return photo;
}

void UploadPhotoButton_Click(object sender, EventArgs e)
{
    if (this.FileUpload1.HasFile)
    {
        var postedFile = this.FileUpload1.PostedFile;
        string address = "http://localhost/upload/?name=file.jpg";
        string result = string.Empty;
        using (var client = new HttpClient())
        {
            using (var request = new HttpRequestMessage(HttpMethod.Put, address))
            {
                request.Content = new StreamContent(postedFile.InputStream);
                request.Content.Headers.ContentType = new MediaTypeHeaderValue(postedFile.ContentType);
                request.Content.Headers.ContentLength = postedFile.ContentLength;

                var response = client.Send(request);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    // :)
                }
                else
                {
                    // :(
                }
            }
        }
    }
    else
    {
        Results.Text = "You have not entered a file.";
    }
}

Jul 15, 2011 at 12:46 PM

I just wanted to follow up with the fix I came up with.  If you change the service method signature to this:

[Description("Uploads a photo.")]
[WebInvoke(UriTemplate = "?name={fileName}", Method = HttpVerbs.PUT)]
public HttpResponseMessage<Photo> UploadPhoto(HttpRequestMessage request, string fileName)
{
    Photo photo = PhotoUploadHandler.HandleUploadPhoto(fileName, request.Content.ContentReadStream);
    return new HttpResponseMessage<Photo>(photo);
}

everything works fine.

-- David