The following forum(s) have migrated to Microsoft Q&A (Preview): Developing Universal Windows apps!
Visit Microsoft Q&A (Preview) to post new questions.

Learn More

 locked
Uploading Image with multipart request Windows Phone 8 RRS feed

  • Question

  • Hello All

    I am trying to upload an image from Windows Phone 8 in a multipart form-data request. The image is uploaded in form of byte array. The image is saved on server, but does not contains details like height, width, dimensions and bit depth, that's why the image is not opening.

    Please let me know how this can be fixed, or what am i missing.

    Thanks in advance


    Deepti

    Wednesday, December 4, 2013 5:51 AM

All replies

  • which API are you using? I used HttpClient API and I could upload multipart form-data without any issue. Following is the code I use for that:

    using (HttpClient client = new HttpClient())
    {
        // Reset the photoStream position
        // If you don't reset the position, the content lenght sent will be 0
        photoStream.Position = 0;
    
        // This is the postdata
        using (MultipartFormDataContent content = new MultipartFormDataContent())
        {
            if (request.Headers != null)
            {
                foreach (KeyValuePair<string, string> header in request.Headers)
                {
                    content.Headers.Add(header.Key, header.Value);
                }
            }
            using (StreamContent streamContent = new StreamContent(photoStream))
            {
                streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse(request.ContentType);
                content.Add(streamContent, multipartName, fileName);
    
                // Post the message and ensure a result.
                using (HttpResponseMessage response = await client.PostAsync(request.TargerUrl, content))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        string responseData = await response.Content.ReadAsStringAsync();
                        return new RestResponse(ResponseStatus.Success, null) { ResponseData = responseData };
                    }
                    else
                    {
                        return new RestResponse(ResponseStatus.Fail, null) { Exception = new Exception(response.ReasonPhrase) };
                    }
                }
            }
        }
    }
    

    Wednesday, December 4, 2013 11:27 AM
  • Hi,

    I tried your code, but at the line 

    using (HttpResponseMessage response = await client.PostAsync(request.TargerUrl, content))

     It gives error: error while copying content to a stream. I searched but found no solution for it. I have to send a json and an image in the content. for this I modified your code a bit. It is given below. Please let me know if I am missing something.

    string URL = "my url string";
    
    try
    {
       using (HttpClient client = new HttpClient())
       {
          // Reset the photoStream position
          // If you don't reset the position, the content lenght sent will be 0
          photoStream.Position = 0;
    
          client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes(string.Format("{0}:{1}", "myusername", "mypassword"))));
    
          client.BaseAddress = new Uri(URL);
    
          // This is the postdata
          using (MultipartFormDataContent content = new MultipartFormDataContent())
          {
             using (StringContent stringContent = new StringContent(jsonData, System.Text.Encoding.UTF8, "text/plain"))
             {
                //stringContent.Headers.ContentType =    MediaTypeHeaderValue.Parse("Content-Type: text/plain");
                                content.Add(stringContent, "surveyResponses");
             }
    
             using (StreamContent streamContent = new StreamContent(photoStream, BufferSize))
             {
                streamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
                                content.Add(streamContent, "files", fileName);
             }
    
             // Post the message and ensure a result.
             using (HttpResponseMessage response = await client.PostAsync(new Uri(URL, UriKind.Absolute), content))
             {
                                var res = response.Content;
             }
          }
       }
    }
    catch (Exception ex)
    {
       var str = ex.Message;
    }

    Thanks


    Deepti


    • Edited by deepti_M Thursday, December 5, 2013 5:57 AM
    Thursday, December 5, 2013 5:57 AM
  • Hi Deepti.

    Please try this code..

    this is working code u have to do some modification according to your code and i ll work...

    public void uploadFile(string upload,string header)
            {
                string fileName = (o["fileName"] == null) ? "null" : o["fileName"].ToString();// file path
                string url = (o["fileServer"] == null) ? "null" : o["fileServer"].ToString(); //url


                Stream formDataStream = new System.IO.MemoryStream();

                var postData = "";
                var boundary = "---------FormBoundary-sadkd22dasd---------";
                var template = "\r\n\r\n" + boundary + "\r\n" +
                               "Content-Dis-data; name=\"{0}\";" + "\r\n\r\n" +
                               "{1}";
                var req = HttpWebRequest.Create(new Uri(url)) as HttpWebRequest;
                req.Method = "POST";
                req.Headers["AppzillonHeader"] = header;
                req.ContentType = "multipart/form-data; boundary=" + boundary;
                postData += string.Format(template, "type", "base64");

                IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();


                Byte[] data;
                try
                {
                    using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Open, isoStore))
                    {
                        data = new byte[isoStream.Length];
                        isoStream.Read(data, 0, data.Length);
                        isoStream.Dispose();
                    }
                    timestamp = DateTime.Now.ToString("ddMMyyyyHHmmssfff");
                    postData += string.Format("\r\n--" + boundary + "\r\n" +
                               "Content-Dis-data; name=\"" + AppResources.AppID + "?" + timestamp + "\"; filename=\"" + file + "\" \r\n" +
                               "Content-Type=text/plain \r\n\r\n");

                    using (MemoryStream ms = new MemoryStream())
                    {
                        ms.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetBytes(postData).Length);
                        ms.Write(data, 0, data.Length);
                        ms.Write(Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"), 0, Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n").Length);

                        reqData = ms.ToArray();
                    }
                    req.ContentLength = reqData.Length;

                    req.BeginGetRequestStream(new AsyncCallback(OnRequestStream), req);
                }
                catch (Exception)
                {
                }
            }

            private void OnRequestStream(IAsyncResult asynchronousResult)
            {

                /// TODO: Exceptions can happen here, catch any WebExceptions, this will happen on a NotFound (or HTTPS failure, or authentication failure)
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                using (Stream sOut = request.EndGetRequestStream(asynchronousResult))
                {
                    sOut.Write(reqData, 0, reqData.Length);
                    reqData = null;
                }
                request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);
            }


            private void FinishWebRequest(IAsyncResult asynchronousResult)
            {
                try
                {
                    HttpWebRequest webRequest = (HttpWebRequest)asynchronousResult.AsyncState;
                    HttpWebResponse response;
                    response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult);
                    Stream streamResponse = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(streamResponse);
                    var Response = streamReader.ReadToEnd();
                    streamResponse.Close();
                    streamReader.Close();
                    response.Close();

                }
                catch (Exception)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        var jsonstring = "{\"errorCode\":\"APZ-FL001 \",\"errorDescription\":\"Network Error\"}";
                        string[] param = { uploadFailureCallBack, jsonstring };
                       gobject.invokeScript("StringToJsonObject", param);
                    });
                }

            }

    Hope this will help you !!

                        
    Thursday, December 5, 2013 8:58 AM
  • Deepti, What error are you getting?
    Thursday, December 5, 2013 9:51 AM
  • My advice is, go and use this Class, is really helpful and is going to avoid you a lot of work:

    MultipartHttpClient

    Kind Regards,


    "The best way to predict the future, is to invent it"

    Wednesday, January 8, 2014 6:23 AM