How to send MultipartForm using POST method in (Windows Phone 8.1) C# - c#

Can any one explain how can i make POST request to a URL on web with different type of data, in my case i have an image and two string type values to send to a server in PHP.
here what i already have done
var stream = await file.OpenStreamForReadAsync();
var streamcontent = new StreamContent(stream);
streamcontent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "photo",
FileName = file.Name
};
streamcontent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
MultipartFormDataContent multipart = new MultipartFormDataContent();
multipart.Add(streamcontent);
try
{
descContent = mytextbox.Text;
var stringcontent = new StringContent(descContent);
stringcontent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("description", descContent));
multipart.Add(stringcontent);
HttpResponseMessage res = await client.PostAsync(new Uri("http://localhost/web/test/index.php"), multipart);
res.EnsureSuccessStatusCode();
mytextbox.Text = await res.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
mytextbox.Text = ex.Message;
}
this code will send the image file but not the description(string), i have searched over the internet but I could not find appropriate answer.
here is the PHP code
if (isset($_FILES['photo']))
{
echo $_FILES["photo"]["name"] . "<br>";
}
else
{
echo "Image: Error<br>";
}
if (isset($_POST['description']))
{
echo $_POST['description'];
}
else
{
echo "Text: Error";
}
any response will be highly appreciated.
thank you

I have search a lot and finally got the way out. here is the code
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://www.yourdomain.com");
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("your string type data you want to post");
form.Add(content, "name");
var stream = await file.OpenStreamForReadAsync();
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "image",
FileName = file.Name
};
form.Add(content);
var response = await client.PostAsync("index.php", form);
mytextblock.Text = response.Content.ReadAsStringAsync();
I wrote it on my blog here is the code. :-)
HappyCoding

Upload files with HTTPWebrequest (multipart/form-data)
http://www.paraesthesia.com/archive/2009/12/16/posting-multipartform-data-using-.net-webrequest.aspx/

Related

How to Pass value along with file upload through webclient C# [duplicate]

How can I send a file and form data with the HttpClient?
I have two ways to send a file or form data. But I want to send both like an HTML form. How can I do that? Thanks.
This is my code:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var client = new HttpClient();
var requestContent = new MultipartFormDataContent();
filename = openFileDialog1.FileName;
array = File.ReadAllBytes(filename);
var imageContent = new ByteArrayContent(array);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("audio/*");
requestContent.Add(imageContent, "audio", "audio.wav");
var values = new Dictionary<string, string>
{
{ "token", "b53b99534a137a71513548091271c44c" },
};
var content = new FormUrlEncodedContent(values);
requestContent.Add(content);
var response = await client.PostAsync("localhost", requestContent);
var responseString = await response.Content.ReadAsStringAsync();
txtbox.Text = responseString.ToString();
}
Here's code I'm using to post form information and a csv file
using (var httpClient = new HttpClient())
{
var surveyBytes = ConvertToByteArray(surveyResponse);
httpClient.DefaultRequestHeaders.Add("X-API-TOKEN", _apiToken);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var byteArrayContent = new ByteArrayContent(surveyBytes);
byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");
var response = await httpClient.PostAsync(_importUrl, new MultipartFormDataContent
{
{new StringContent(surveyId), "\"surveyId\""},
{byteArrayContent, "\"file\"", "\"feedback.csv\""}
});
return response;
}
This is for .net 4.5.
Note the \" in the MultipartFormDataContent. There is a bug in MultipartFormDataContent.
In 4.5.1 MultipartFormDataContent wraps the data with the correct quotes.
Update: This link to the bug no longer works since the have retired Microsoft Connect.
Here's code I'm using a method to send file and data from console to API
static async Task uploaddocAsync()
{
MultipartFormDataContent form = new MultipartFormDataContent();
Dictionary<string, string> parameters = new Dictionary<string, string>();
//parameters.Add("username", user.Username);
//parameters.Add("FullName", FullName);
HttpContent DictionaryItems = new FormUrlEncodedContent(parameters);
form.Add(DictionaryItems, "model");
try
{
var stream = new FileStream(#"D:\10th.jpeg", FileMode.Open);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(#"http:\\xyz.in");
HttpContent content = new StringContent("");
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "uploadedFile1",
FileName = "uploadedFile1"
};
content = new StreamContent(stream);
form.Add(content, "uploadedFile1");
client.DefaultRequestHeaders.Add("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.dsfdsfdsfdsfsdfkhjhjkhjk.vD056hXETFMXYxOaLZRwV7Ny1vj-tZySAWq6oybBr2w");
var response = client.PostAsync(#"\api\UploadDocuments\", form).Result;
var k = response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
}
}

Reading Multipart Data from Xamarin

We have a requirement of sending the jpeg files of a given directory to a Xamarin App.
Following is the code in the Web API.
public HttpResponseMessage DownloadMutipleFiles()
{
name = "DirectoryName";
var content = new MultipartContent();
var ids = new List<int> { 1,2};
var objectContent = new ObjectContent<List<int>>(ids, new System.Net.Http.Formatting.JsonMediaTypeFormatter());
content.Add(objectContent);
var file1Content = new StreamContent(new FileStream(#"D:\Photos\" + name+"\\"+ "BL1408037_20191031124058_0.jpg", FileMode.Open));
file1Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(file1Content);
var file2Content = new StreamContent(new FileStream(#"D:\Photos\" + name + "\\" + "BL1408037_20191031124058_1.jpg", FileMode.Open));
file2Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(file2Content);
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = content;
return response;
}
Can some one help out with how to read from Xamarin app? Thanks in advance
This is the function I was able to use to send an image as a multi part data file! I just took the byte array given to me by the Xamarin Essentials image picker and passed it into this function:
public async Task SubmitImage(byte[] image, string imageName)
{
using (var client = new HttpClient())
{
string url = $"..."; // URL goes here
var token = Preferences.Get("AccessToken", "");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var stream = new MemoryStream(image);
var content = new StreamContent(stream);
//Without a name we can't actually put the file in IFormFile. We need the equivalent
//"name" value to be "file" (used if you upload via an <input> tag). We could call it
//anything but file is simple
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = imageName,
Name = "file"
};
content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(content);
var result = await client.PostAsync(url, multipartContent);
}
}
You can test this using a console application as well and just send over a picture from your computer, instead of doing this through the app

xamarin post not making it to api

Hi my xamarin post is not making it to my rest api.I keep getting "An error occure while sending the request" all my other posts work but just not this one. I have set network permissions as my login and geting data works. any help would be great. below is a code snippet.
public async Task<string> PostChecklist(string json)
{
try
{
JToken rootObject = JObject.Parse(json);
HttpClient httpClient = new HttpClient();
MultipartFormDataContent multipartContent = new MultipartFormDataContent();
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + TokenId);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
string sFile = (string)rootObject["Answers"]["Signature"];
//Get file
if (!File.Exists((string)rootObject["Answers"]["Signature"]))
{
return "no signature found";
}
FileStream fs = File.OpenRead((string)rootObject["Answers"]["Signature"]);
StreamContent streamContent = new StreamContent(fs);
streamContent.Headers.Add("Content-Type", "application/octet-stream");
multipartContent.Add(streamContent, "signature", "signature.png");
#region Upload images
JToken jobectImages = rootObject["Images"];
foreach (var item in jobectImages)
{
foreach (var internalitem in item)
{
foreach (var imageGroup in internalitem)
{
foreach (JObject image in imageGroup)
{
JToken tokenName, tokenFileName;
image.TryGetValue("FileName", out tokenName);
image.TryGetValue("FilePath", out tokenFileName);
string FileName = tokenName.ToString();
string FilePath = tokenFileName.ToString();
//Get file
FileStream fs2 = File.OpenRead(FilePath);
StreamContent streamContent2 = new StreamContent(fs);
streamContent2.Headers.Add("Content-Type", "application/octet-stream");
multipartContent.Add(streamContent2, FileName, FileName);
}
}
}
}
#endregion
var contentJson = new StringContent(json);
contentJson.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "JSONString"
};
var contentLong = new StringContent("26");
contentLong.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "Long"
};
var contentLat = new StringContent("96");
contentLat.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "Lat"
};
multipartContent.Add(contentJson);
multipartContent.Add(contentLong);
multipartContent.Add(contentLat);
var response = await httpClient.PostAsync(GlobalVariables.url + "/checkurl/answers/v12", multipartContent).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
Information = await response.Content.ReadAsStringAsync();
JObject jsonOther = JObject.Parse(Information);
if(((String)jsonOther["status"]) == "success")
{
return "";
}
else
{
return (String)jsonOther["message"];
}
}
else{
return "Server Error";
}
}
catch(Exception e)
{
return e.ToString();
}
}
Cool Looks like there was a problem with one of my MultipartFormDataContent when trying to attach images, if i dont attach an image it does work, so the Url post was breaking. Simulator cant take images so never had the problem.. Thanks anyways
MultipartFormDataContent has a bug with how it generates request content based on the order the headers and body are added.
For example
StreamContent streamContent = new StreamContent(fs);
streamContent.Headers.Add("Content-Type", "application/octet-stream");
multipartContent.Add(streamContent, "signature", "signature.png");
Will cause the content type header to be added before the content disposition header,
-----------------------------some boundary value here
Content-Type: application/octet-stream
Content-Disposition: form-data; name=signature; filename=signature.png
which is known to cause issues with how some servers read the body/content of the request
Instead make sure to set the content composition header first and also make sure that the name and file name are wrapped in double quotes before adding it to the multi-part form data content
StreamContent streamContent = new StreamContent(fs);
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") {
Name = "\"signature\"",
Filename = "\"signature.png\""
};
streamContent.Headers.Add("Content-Type", "application/octet-stream");
multipartContent.Add(streamContent);
The same will need to be done for the other section where images are added
//Get file
FileStream fs2 = File.OpenRead(FilePath);
StreamContent streamContent2 = new StreamContent(fs);
streamContent2.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") {
Name = string.Format("\"{0}\"", FileName),
Filename = string.Format("\"{0}\"", FileName),
};
streamContent2.Headers.Add("Content-Type", "application/octet-stream");
multipartContent.Add(streamContent2);

How to implement a multipart post request in c# wp8.1 (winrt)

Already second day trying to implement a multipart post request, but so far I have failed.
Task: to send 1 or 2 pictures to the server.
Please tell me how to do this in Windows Phone 8.1 (WinRT). Already tried a huge number of links on the Internet, but nothing happened.
p.s. in the description of the API server written that you must submit a request in the following format.
{
"type": "object",
"properties": {
"files": {
"type": "array",
"items": {
"type": "file"
}
}
}
}
Yes, of course. Here is my code. I searched the Internet and eventually tried to implement this. Interestingly, it worked and sent the data to the server. only the North returned the error: "data error", so I sent out in the wrong format. I assume it's because not json created structure, about which I wrote above.
public async static Task<bool> UploadFiles(StorageFile file)
{
var streamData = await file.OpenReadAsync();
var bytes = new byte[streamData.Size];
using (var dataReader = new DataReader(streamData))
{
await dataReader.LoadAsync((uint)streamData.Size);
dataReader.ReadBytes(bytes);
}
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
System.Net.Http.MultipartFormDataContent form = new System.Net.Http.MultipartFormDataContent();
form.Add(new System.Net.Http.StringContent(UserLogin), "username");
form.Add(new System.Net.Http.StringContent(UserPassword), "password");
form.Add(new System.Net.Http.ByteArrayContent(bytes, 0, bytes.Length), "files", "items");
form.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(UploadFilesURI, form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
return true;
}
Sorry for this style of code. Haven't quite figured out how to insert it correctly in the posts
I eventually solved my problem. The code give below
public async static Task<string> UploadFiles(StorageFile[] files)
{
try
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("ru"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", "token=" + SessionToken);
var content = new System.Net.Http.MultipartFormDataContent();
foreach (var file in files)
{
if (file != null)
{
var streamData = await file.OpenReadAsync();
var bytes = new byte[streamData.Size];
using (var dataReader = new DataReader(streamData))
{
await dataReader.LoadAsync((uint)streamData.Size);
dataReader.ReadBytes(bytes);
}
string fileToUpload = file.Path;
using (var fstream = await file.OpenReadAsync())
{
var streamContent = new System.Net.Http.ByteArrayContent(bytes);
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "files[]",
FileName = Path.GetFileName(fileToUpload),
};
content.Add(streamContent);
}
}
}
var response = await client.PostAsync(new Uri(UploadFilesURI, UriKind.Absolute), content);
var contentResponce = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<API.ResponceUploadFiles.RootObject>(contentResponce);
return result.cache;
}
catch { return ""; }
}

Upload files to Google Drive in Windows Store App

UPDATE 1
I think I am using incorrect URL, this doc says to use "https://www.googleapis.com/drive/v2/files" & this doc says to use "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart". Though I am getting same 400 bad request.
Can I use Google Drive upload REST API in background uploader class?
I am following this doc from Google Drive to upload files but I am getting 400 - Bad request. What's wrong with my code?
public static async Task UploadFileAsync(Token AuthToken, StorageFile file, DriveFile objFolder)
{
try
{
if (!httpClient.DefaultRequestHeaders.Contains("Authorization"))
{
httpClient.DefaultRequestHeaders.Add("Authorization", AuthToken.TokenType + " " + AuthToken.AccessToken);
}
var JsonMessage = JsonConvert.SerializeObject(objFolder);
/*JsonMessage = {"title":"c4611_sample_explain.pdf","mimeType":"application/pdf","parents":[{"id":"root","kind":"drive#fileLink"}]}*/
var JsonReqMsg = new StringContent(JsonMessage, Encoding.UTF8, "application/json");
var fileBytes = await file.ToBytesAsync();
var form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(fileBytes));
form.Add(JsonReqMsg);
form.Headers.ContentType = new MediaTypeHeaderValue("multipart/related");
var UploadReq = await httpClient.PostAsync(new Uri("https://www.googleapis.com/drive/v2/files?uploadType=multipart"), form);
if (UploadReq.IsSuccessStatusCode)
{
var UploadRes = await UploadReq.Content.ReadAsStringAsync();
}
else
{
}
}
catch (Exception ex)
{
}
}
You must use https://www.googleapis.com/upload/drive/v2/files
I have a working sample here (sorry, the JSON string is hard coded):
// Multipart file upload
HttpClient client = new HttpClient();
string uriString = "https://www.googleapis.com/upload/drive/v2/files?key=<your-key>&access_token=<access-token>&uploadType=multipart";
Uri uri = new Uri(uriString);
HttpContent metadataPart = new StringContent(
"{ \"title\" : \"My File\"}",
Encoding.UTF8,
"application/json");
HttpContent mediaPart = new StringContent(
"The naughty bunny ate all the cookies.",
Encoding.UTF8,
"text/plain");
MultipartContent multipartContent = new MultipartContent();
multipartContent.Add(metadataPart);
multipartContent.Add(mediaPart);
HttpResponseMessage response = await client.PostAsync(uri, multipartContent);
string responseString = await response.Content.ReadAsStringAsync();

Categories

Resources