Upload image to server from windows phone 8.1 using windows.web.http - windows-phone-8.1

Iam currently working with windows phone 8.1 application.Iam really new to this
i want to know how to upload an image to webservice from windows phone 8.1 by using windows.web.http.Please help me i want the full details step by step.Thanks in advance

You can do it this way:
Uri resourceAddress = new Uri("http://www.someurl.com/~?lalala");
StorageFile img = await ApplicationData.Current.LocalFolder.GetFileAsync("ImageName.jpg");
Stream inputStream = await img.OpenStreamForReadAsync();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, resourceAddress);
HttpMultipartContent cont = new HttpMultipartContent();
cont.Add(new HttpStreamContent(inputStream.AsInputStream()));
cont.Headers.ContentType = new HttpMediaTypeHeaderValue("image/jpeg");
request.Content = cont;
request.Headers.Connection.Add(new HttpConnectionOptionHeaderValue("Keep-Alive"));
request.Content.Headers.ContentLength = (ulong)inputStream.Length;
HttpResponseMessage response = await httpClient.SendRequestAsync(request);
if (response.StatusCode == HttpStatusCode.Ok)
{
return true;
}
or you can replace last "if" with:
using (Stream responseStream = (await response.Content.ReadAsInputStreamAsync()).AsStreamForRead())
{
StreamReader reader = new StreamReader(responseStream);
string result = await reader.ReadToEndAsync();
}
Here is good link with official samples on github: HttpClient sample

Related

How to upload image to server (using POST) which return json in Windows Phone 8.1 RT?

I am making an app which can upload image to a server (the server works well), and I use this method to upload my image to it, but when I get the respond from the result, it return a null string, can you explain for me what did I do wrong.
I followed this method: How to upload file to server with HTTP POST multipart/form-data
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
byte[] bytes = await Converter.GetBytesAsync(storageFile);
form.Add(new ByteArrayContent(bytes, 0, bytes.Count()), "\"upload-file\"", "\"test.jpg\"");
HttpResponseMessage response = await httpClient.PostAsync("my-url", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
Debug.WriteLine("res: " + sd); // this return a null string
The request return like this:
--a81d2efe-5f2e-4f84-83b9-261329bee20b
Content-Disposition: form-data; name="upload-file"; filename="test.jpg"; filename*=utf-8''%22test.jpg%22
����Ivg?�aEQ�.�����(��9%�=��>�C�~/�QG$�֨������(�`������QE��Z��
Can you help me please!
P/s: Here is my convert method
public static async Task<byte[]> GetBytesAsync(StorageFile file)
{
byte[] fileBytes = null;
if (file == null) return null;
using (var stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
return fileBytes;
}
This might help
private async Task<string> UploadImage(StorageFile file)
{
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("fileToUpload");
form.Add(content, "fileToUpload");
var stream = await file.OpenStreamForReadAsync();
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileToUpload",
FileName = file.Name
};
form.Add(content);
var response = await client.PostAsync("my-url", form);
return response.Content.ReadAsStringAsync().Result;
}
Use ByteArrayContent instead of StringContent. That Should work.
And if you are expecting a stream-response you should use ReadAsStreamAsync instaed of ReadAsStringAsync.

get a response from httpclient postasync in wp8 app

i have the following code that uploads a photo to a web service , i need to get the response from the service , and i'm using httpclient class here's my code
var fileUploadUrl = Globals.baseUrl + "/laravelProjects/VisWall/public/test";
var client = new HttpClient();
photoStream.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(photoStream), "image", "koko");
await client.PostAsync(fileUploadUrl, content).ContinueWith((postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
}
i've just found the answer you shoud read string async from the results content
string stringResponse =await postTask.Content.ReadAsStringAsync();

Sending a photo to server using httpclient class windows phone 8

i'm trying to send a photo to a server using httpclient class but every time i try i get a 0 byte file , here's my code for sending the image
if (e.ChosenPhoto != null)
{
var fileUploadUrl = Globals.baseUrl + "/laravelProjects/VisWall/public/test2";
var client = new HttpClient();
photoStream.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(e.ChosenPhoto), "image", fileName);
HttpResponseMessage result = new HttpResponseMessage();
await client.PostAsync(fileUploadUrl, content).ContinueWith((postTask) =>
{
try
{
result = postTask.Result.EnsureSuccessStatusCode();
}
catch (Exception exc)
{
MessageBox.Show("errorrrrrr");
}
});
}
i've also checked the length of e.ChoosenPhoto and it's not 0
try this piece of code by using MultipartFormDataContent:
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(token), "token");
var imageForm = new ByteArrayContent(imagen, 0, imagen.Count());
imagenForm.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
form.Add(imagenForm, "image", "nameholder.jpg");
HttpResponseMessage response = await httpClient.PostAsync("your_url_here", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string result = response.Content.ReadAsStringAsync().Result;
You could refer these too:
Uploading image and data as multi part content - windows phone 8
How to upload file to server with HTTP POST multipart/form-data
There are plenty of samples out there, which I've not mentioned here. It would be great if you could give a search before you post here.

Link is not opening in Windows Phone 8.1

I have such code, that work on my Console Project in VS2012 for Desktop, but not work in VS2013 for WP8.
url = "http://lenta.ru/photo/2014/06/23/blackwidow/"
WebRequest request = WebRequest.Create(url);
WebResponse response = await request.GetResponseAsync(); /*from here programm doesn't work on wp8, but works on PC Console Project on VS2012*/
Stream data = response.GetResponseStream();
Why this code work on console project, but not work from my WP8 app?
fix.
Problem is solved by using HttpCLient instead of WebRequest.
HttpClient client = new HttpClient();
try
{
var result = await client.GetStringAsync(url);
}
catch
{
}
client.Dispose();
Problem is solved by using HttpCLient instead of WebRequest.
HttpClient client = new HttpClient();
try
{
var result = await client.GetStringAsync(url);
}
catch
{
}
client.Dispose();

HttpClient dosen't get data after update WP8

I have this code to get JSON data from an API for WP8:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(mainURL.ToString());
HttpResponseMessage response = await client.GetAsync("");
string res = await response.Content.ReadAsStringAsync();
var root = await JsonConvert.DeserializeObjectAsync<Rootobject>(res);
Everything works perfectly, but when I update data on the web API from the web site and try to retrieve data again using this code it gets the old data even though accessing the URL in a browser it gets the new data.
When I debug line by line, I see that the "response" object contains the old data.
The only way I have found to fix this is to rebuild the project in this way it works.
How can I properly get the updated data?
There may be some caching involved. Tried adding some random string to the URL, like
client.BaseAddress = new Uri(mainURL.ToString()+"&random="+DateTime.Now.Ticks);
I have same kind of problem. I tried this this may be help you.
HttpWebRequest request = HttpWebRequest.CreateHttp(mainURL.ToString());
request.Method = "GET or Post";
request.BeginGetResponse(ResponseCallBack, request);
void ResponseCallBack(IAsyncResult asyncResult)
{
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
string jsonString = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(Rootobject));
Rootobject yourdata= dataContractJsonSerializer.ReadObject(memoryStream) as Rootobject;
}
}
}