Python code to c# .net for HTTP Post to API - c#

I need help converting the follow Python code to c# .net. This code is posting/uploading a text file to a webserver. The Python script has been tested and works. I have tried a few solutions with HTTPClient and WebRequest with no luck. Any guidance will be greatly appreciated.
# request a session
client = requests.session()
# Establish the URL
newurl = 'https://localhost/filedist/upload/'
source_file = 'data/test.txt'
headers = {'Authorization': 'Token MYTOKEN'}
# Populate the values with our environment and target path
values = dict(environment='dev', path='Business/Tools')
files = dict(file=open(source_file, 'rb'))
r = client.post(newurl, files=files, data=values, headers=headers)
Here is my latest attempt, which currently is getting a 'Forbidden' error.
public static async Task<string> UploadFile(string path, string fileName)
{
var client = new HttpClient();
string NewURL = "https://localhost/filedist/upload/";
string SourceFile = path;
var content = new MultipartFormDataContent();
client.DefaultRequestHeaders.Add("Authorization", "Token MYTOKEN");
Stream fs = System.IO.File.Open(path, FileMode.Open, FileAccess.Read, FileShare.None);
content.Add(CreateFileContent(fs, fileName, "text/plain"));
var parameters = new Dictionary<string, string> { { "environment", "dev" }, { "path", "Business/Tools" } };
content.Add(new FormUrlEncodedContent(parameters));
var response = await client.PostAsync(NewURL, content);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
return "true";
}
else
{
return "false";
}
}
private static StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
{
try
{
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
{
Name = "UploadedFile",
FileName = "\"" + fileName + "\""
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return fileContent;
}
catch (Exception ex)
{
return null;
}
}
Thanks

I am not 100% on this, but I don't think you can set the authorization header that way. Try using the client authorization header type.
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Token", "MYTOKEN");

Related

How to implement WebClient.UploadFileAsync with HttpClient? [duplicate]

Does anyone know how to use the HttpClient in .Net 4.5 with multipart/form-data upload?
I couldn't find any examples on the internet.
my result looks like this:
public static async Task<string> Upload(byte[] image)
{
using (var client = new HttpClient())
{
using (var content =
new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
{
content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg");
using (
var message =
await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content))
{
var input = await message.Content.ReadAsStringAsync();
return !string.IsNullOrWhiteSpace(input) ? Regex.Match(input, #"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null;
}
}
}
}
It works more or less like this (example using an image/jpg file):
async public Task<HttpResponseMessage> UploadImage(string url, byte[] ImageData)
{
var requestContent = new MultipartFormDataContent();
// here you can specify boundary if you need---^
var imageContent = new ByteArrayContent(ImageData);
imageContent.Headers.ContentType =
MediaTypeHeaderValue.Parse("image/jpeg");
requestContent.Add(imageContent, "image", "image.jpg");
return await client.PostAsync(url, requestContent);
}
(You can requestContent.Add() whatever you want, take a look at the HttpContent descendant to see available types to pass in)
When completed, you'll find the response content inside HttpResponseMessage.Content that you can consume with HttpContent.ReadAs*Async.
This is an example of how to post string and file stream with HTTPClient using MultipartFormDataContent. The Content-Disposition and Content-Type need to be specified for each HTTPContent:
Here's my example. Hope it helps:
private static void Upload()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");
using (var content = new MultipartFormDataContent())
{
var path = #"C:\B2BAssetRoot\files\596086\596086.1.mp4";
string assetName = Path.GetFileName(path);
var request = new HTTPBrightCoveRequest()
{
Method = "create_video",
Parameters = new Params()
{
CreateMultipleRenditions = "true",
EncodeTo = EncodeTo.Mp4.ToString().ToUpper(),
Token = "x8sLalfXacgn-4CzhTBm7uaCxVAPjvKqTf1oXpwLVYYoCkejZUsYtg..",
Video = new Video()
{
Name = assetName,
ReferenceId = Guid.NewGuid().ToString(),
ShortDescription = assetName
}
}
};
//Content-Disposition: form-data; name="json"
var stringContent = new StringContent(JsonConvert.SerializeObject(request));
stringContent.Headers.Add("Content-Disposition", "form-data; name=\"json\"");
content.Add(stringContent, "json");
FileStream fs = File.OpenRead(path);
var streamContent = new StreamContent(fs);
streamContent.Headers.Add("Content-Type", "application/octet-stream");
//Content-Disposition: form-data; name="file"; filename="C:\B2BAssetRoot\files\596090\596090.1.mp4";
streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(path) + "\"");
content.Add(streamContent, "file", Path.GetFileName(path));
//content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
Task<HttpResponseMessage> message = client.PostAsync("http://api.brightcove.com/services/post", content);
var input = message.Result.Content.ReadAsStringAsync();
Console.WriteLine(input.Result);
Console.Read();
}
}
}
Try this its working for me.
private static async Task<object> Upload(string actionUrl)
{
Image newImage = Image.FromFile(#"Absolute Path of image");
ImageConverter _imageConverter = new ImageConverter();
byte[] paramFileStream= (byte[])_imageConverter.ConvertTo(newImage, typeof(byte[]));
var formContent = new MultipartFormDataContent
{
// Send form text values here
{new StringContent("value1"),"key1"},
{new StringContent("value2"),"key2" },
// Send Image Here
{new StreamContent(new MemoryStream(paramFileStream)),"imagekey","filename.jpg"}
};
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(actionUrl.ToString(), formContent);
string stringContent = await response.Content.ReadAsStringAsync();
return response;
}
Here is another example on how to use HttpClient to upload a multipart/form-data.
It uploads a file to a REST API and includes the file itself (e.g. a JPG) and additional API parameters. The file is directly uploaded from local disk via FileStream.
See here for the full example including additional API specific logic.
public static async Task UploadFileAsync(string token, string path, string channels)
{
// we need to send a request with multipart/form-data
var multiForm = new MultipartFormDataContent();
// add API method parameters
multiForm.Add(new StringContent(token), "token");
multiForm.Add(new StringContent(channels), "channels");
// add file and directly upload it
FileStream fs = File.OpenRead(path);
multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));
// send request to API
var url = "https://slack.com/api/files.upload";
var response = await client.PostAsync(url, multiForm);
}
Here's a complete sample that worked for me. The boundary value in the request is added automatically by .NET.
var url = "http://localhost/api/v1/yourendpointhere";
var filePath = #"C:\path\to\image.jpg";
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
FileStream fs = File.OpenRead(filePath);
var streamContent = new StreamContent(fs);
var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(imageContent, "image", Path.GetFileName(filePath));
var response = httpClient.PostAsync(url, form).Result;
Example with preloader Dotnet 3.0 Core
ProgressMessageHandler processMessageHander = new ProgressMessageHandler();
processMessageHander.HttpSendProgress += (s, e) =>
{
if (e.ProgressPercentage > 0)
{
ProgressPercentage = e.ProgressPercentage;
TotalBytes = e.TotalBytes;
progressAction?.Invoke(progressFile);
}
};
using (var client = HttpClientFactory.Create(processMessageHander))
{
var uri = new Uri(transfer.BackEndUrl);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", AccessToken);
using (MultipartFormDataContent multiForm = new MultipartFormDataContent())
{
multiForm.Add(new StringContent(FileId), "FileId");
multiForm.Add(new StringContent(FileName), "FileName");
string hash = "";
using (MD5 md5Hash = MD5.Create())
{
var sb = new StringBuilder();
foreach (var data in md5Hash.ComputeHash(File.ReadAllBytes(FullName)))
{
sb.Append(data.ToString("x2"));
}
hash = result.ToString();
}
multiForm.Add(new StringContent(hash), "Hash");
using (FileStream fs = File.OpenRead(FullName))
{
multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(FullName));
var response = await client.PostAsync(uri, multiForm);
progressFile.Message = response.ToString();
if (response.IsSuccessStatusCode) {
progressAction?.Invoke(progressFile);
} else {
progressErrorAction?.Invoke(progressFile);
}
response.EnsureSuccessStatusCode();
}
}
}
I'm adding a code snippet which shows on how to post a file to an API which has been exposed over DELETE http verb. This is not a common case to upload a file with DELETE http verb but it is allowed. I've assumed Windows NTLM authentication for authorizing the call.
The problem that one might face is that all the overloads of HttpClient.DeleteAsync method have no parameters for HttpContent the way we get it in PostAsync method
var requestUri = new Uri("http://UrlOfTheApi");
using (var streamToPost = new MemoryStream("C:\temp.txt"))
using (var fileStreamContent = new StreamContent(streamToPost))
using (var httpClientHandler = new HttpClientHandler() { UseDefaultCredentials = true })
using (var httpClient = new HttpClient(httpClientHandler, true))
using (var requestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri))
using (var formDataContent = new MultipartFormDataContent())
{
formDataContent.Add(fileStreamContent, "myFile", "temp.txt");
requestMessage.Content = formDataContent;
var response = httpClient.SendAsync(requestMessage).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
// File upload was successfull
}
else
{
var erroResult = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
throw new Exception("Error on the server : " + erroResult);
}
}
You need below namespaces at the top of your C# file:
using System;
using System.Net;
using System.IO;
using System.Net.Http;
P.S. You are seeing a number of using blocks(IDisposable pattern) in the above code snippet which doesn't look very clean. Unfortunately, the syntax of using construct doesn't support initializing multiple variables in single statement.
X509Certificate clientKey1 = null;
clientKey1 = new X509Certificate(AppSetting["certificatePath"],
AppSetting["pswd"]);
string url = "https://EndPointAddress";
FileStream fs = File.OpenRead(FilePath);
var streamContent = new StreamContent(fs);
var FileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
FileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("ContentType");
var handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(clientKey1);
handler.ServerCertificateValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
using (var client = new HttpClient(handler))
{
// Post it
HttpResponseMessage httpResponseMessage = client.PostAsync(url, FileContent).Result;
if (!httpResponseMessage.IsSuccessStatusCode)
{
string ss = httpResponseMessage.StatusCode.ToString();
}
}
public async Task<object> PassImageWithText(IFormFile files)
{
byte[] data;
string result = "";
ByteArrayContent bytes;
MultipartFormDataContent multiForm = new MultipartFormDataContent();
try
{
using (var client = new HttpClient())
{
using (var br = new BinaryReader(files.OpenReadStream()))
{
data = br.ReadBytes((int)files.OpenReadStream().Length);
}
bytes = new ByteArrayContent(data);
multiForm.Add(bytes, "files", files.FileName);
multiForm.Add(new StringContent("value1"), "key1");
multiForm.Add(new StringContent("value2"), "key2");
var res = await client.PostAsync(_MEDIA_ADD_IMG_URL, multiForm);
}
}
catch (Exception e)
{
throw new Exception(e.ToString());
}
return result;
}

SharePointOnlineCredentials can't find account and

I'm trying to connect to my Company's sharepoint but the credentials I use (my email and password) are not recognized and an error is thrown on the ExecuteQuery line. Also when I try and get the files using relative paths or url paths, every single property throws a Microsoft.SharePoint.Client.PropertyOrFieldNotInitializedException.
private static readonly HttpClient client = new HttpClient();
[FunctionName("SendFiles")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req,
ILogger log)
{
ClientContext context = new ClientContext("https://abc.sharepoint.com/sites/a-b");
SecureString secureString = new SecureString();
foreach(char c in "dummypass")
{
secureString.AppendChar(c);
}
context.Credentials = new SharePointOnlineCredentials("a.b#faktion.com", secureString);
Web site = context.Web;
string jsonInput = req.Content.ReadAsStringAsync().Result;
SendFilesInput input = JsonConvert.DeserializeObject<SendFilesInput>(jsonInput);
string url = "https://a.b.com/gql/api/organisations/" + input.OrganisationId + "/projects/" + input.ProjectId + "/process";
string response = null;
bool succesfullRequest = false;
MultipartFormDataContent formdata = new MultipartFormDataContent();
try
{
foreach (var filePath in input.Files)
{
// create filestream content
var fileurl = "https://abc.sharepoint.com/sites/a-b" + "/" + filePath;
Microsoft.SharePoint.Client.File temp = site.GetFileByServerRelativeUrl(filePath);
Microsoft.SharePoint.Client.File temp2 = site.GetFileByUrl(fileurl);
ClientResult<Stream> crstream = temp.OpenBinaryStream();
ClientResult<Stream> crstream2 = temp2.OpenBinaryStream();
context.Load(temp);
context.Load(temp2);
context.ExecuteQuery();
var tempfile = Path.GetTempFileName();
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
if (crstream.Value != null)
{
crstream.Value.CopyTo(fs);
}
HttpContent content = new StreamContent(fs);
string name = GetFileName(filePath);
content.Headers.Add("Content-Type", GetFileType(name));
formdata.Add(content, "files", name);
System.IO.File.Decrypt(tempfile);
}
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", input.BearerToken);
// send content to the backend and parse result
var resultPost = client.PostAsync(url, formdata).Result;
response = resultPost.Content.ReadAsStringAsync().Result;
succesfullRequest = resultPost.IsSuccessStatusCode;
}
// I absolutely want to catch every exception and pass these along to the workflow
catch (Exception ex)
{
req.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
// if something went wrong in the backend, throw an error
if (!succesfullRequest)
{
req.CreateErrorResponse(HttpStatusCode.BadRequest, "Something went wrong during the upload process");
}
[...] // rest is not important
Error:
The sign-in name or password does not match one in the Microsoft account system.

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);

POST StreamContent with Multiple Files

The code snippet below successfully HttpPosts a single file to WebAPI. I'd like expand it to build StreamContent containing multiple files (similar to Fiddler multi-file posts).
I know I should be adding a "boundary" to the StreamContent, but I'm not sure exactly where. I'd like to eventually convert the FileStream/Stream parameters to be a List so I can iterate through the collection and build StreamContent to POST.
Let me know if this post makes any sense. I'd appreciate any suggestions.
Thanks in advance!
public async Task<HttpStatusCode> UploadOrderFile(FileStream imageFileStream, string filename, string contentType = "image/png")
{
JsonApiClient._client.DefaultRequestHeaders.Clear();
var content = new MultipartFormDataContent
{
JsonApiClient.CreateFileContent(imageFileStream, filename, contentType)
};
JsonApiClient._client.DefaultRequestHeaders.Add("Authorization",
" Bearer " + JsonApiClient.Token.AccessToken);
var response = await JsonApiClient._client.PostAsync("api/UploadFile", content);
response.EnsureSuccessStatusCode();
return response.StatusCode;
}
internal static StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
{
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"files\"",
FileName = "\"" + fileName + "\""
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return fileContent;
}
EDIT: I do not have any issues receiving and saving the posted files. The issue lies in creating the StreamContent necessary to post multiple files.
This is a solution that I tried that works for me. Nothing was changed in CreateFileContent. I just simply converted parameters into collections, iterated through each collection, and added new MultiPartFormDataContent out of multiple StreamContent. The boundary was also added to the MultipartFormDataContent object. If you see anything that is inefficient or plain wrong, let me know. Thanks!
public async Task<HttpStatusCode> UploadOrderFile(List<FileStream> imageFileStream, List<string> filename, string salesOrderNo, List<string> contentType)
{
JsonApiClient._client.DefaultRequestHeaders.Clear();
var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
var content = new MultipartFormDataContent(boundary);
for (var i = 0; i < imageFileStream.Count; i++)
{
content.Add(JsonApiClient.CreateFileContent(imageFileStream[i], filename[i], contentType[i]));
}
JsonApiClient._client.DefaultRequestHeaders.Add("Authorization",
" Bearer " + JsonApiClient.Token.AccessToken);
var response = await JsonApiClient._client.PostAsync("api/UploadFile", content);
response.EnsureSuccessStatusCode();
return response.StatusCode;
}
internal static StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
{
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"files\"",
FileName = "\"" + fileName + "\""
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return fileContent;
}
Try this approach
public HttpResponseMessage Post()
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach(string file in httpRequest.Files)
{
var content = new MultipartFormDataContent
{
JsonApiClient.CreateFileContent(postedFile.InputStream, postedFile.FileName, postedFile.ContentType)
};
// NOTE: To store in memory use postedFile.InputStream
}
return Request.CreateResponse(HttpStatusCode.Created);
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
internal static StreamContent CreateFileContent(Stream stream, string fileName, string contentType)
{
var fileContent = new StreamContent(stream);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"files\"",
FileName = "\"" + fileName + "\""
};
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return fileContent;
}

How to send MultipartForm using POST method in (Windows Phone 8.1) 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/

Categories

Resources