Reading Multipart Data from Xamarin - c#

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

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)
{
}
}

Unable to pass file to web api in ASP.NET MVC Core

I am working on an angular and .NET Core application. I have to pass the file uploaded from angular to WEB API. My code is:
public async Task ImportDataScienceAnalytics(string authToken, IFormFile file)
{
var baseUrl = Import.GetBaseURL();
var client = new RestClientExtended(baseUrl + "algorithm/import");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", authToken);
string jsonBody = JsonConvert.SerializeObject(file);
request.AddJsonBody(jsonBody);
var response = await client.ExecutePostTaskAsync(request);
var result = response.Content;
}
Issue is that i get "No Attachment Found". I think the issue is because of IFormFile. How can i resolve this issue so that i can upload the file to web api.
It seems that you'd like to post uploaded file to an external API from your API action using RestClient, you can refer to the following code snippet.
var client = new RestClient(baseUrl + "algorithm/import");
var request = new RestRequest(Method.POST);
request.AddHeader("authorization", authToken);
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
request.AddFile("file", fileBytes, file.FileName, "application/octet-stream");
}
//...
Testing code of Import action
public IActionResult Import(IFormFile file)
{
//...
//code logic here
You need to make following changes to the code.
var baseUrl = Import.GetBaseURL();
var client = new RestClientExtended(baseUrl + "algorithm/import");
var request = new RestRequest(Method.POST);
byte[] data;
using (var br = new BinaryReader(file.OpenReadStream()))
data = br.ReadBytes((int)file.OpenReadStream().Length);
ByteArrayContent bytes = new ByteArrayContent(data);
MultipartFormDataContent multiContent = new MultipartFormDataContent
{
{ bytes, "file", file.FileName }
};
//request.AddHeader("authorization", authToken);
//string jsonBody = JsonConvert.SerializeObject(file);
//request.AddJsonBody(jsonBody);
/// Pass the multiContent into below post
var response = await client.ExecutePostTaskAsync(request);
var result = response.Content;
Do not forget to pass the variable multiContent into the post call.

How i can post file to web API from C#?

I need to post a file from asp application to an API
the file will be uploaded through <asp:FileUpload />
in the back end, i will receive the file and send it to Web API method
the web API method will contain the code
var root = HttpContext.Current.Server.MapPath("~/App_Data/Uploadfiles");
var provider = new MultipartFormDataStreamProvider(root);
var result = await Request.Content.ReadAsMultipartAsync(provider);
the asp page will has the code
using (System.IO.Stream fs = fuID.PostedFile.InputStream)
{
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "http://localhost:5000/path"))
{
request.Headers.TryAddWithoutValidation("Accept", "application/json, text/plain, */*");
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + AppUserContext.Token);
request.Headers.TryAddWithoutValidation("x-language", "ar");
// Iam Not Sure of this line
request.Content = new StringContent("Content-Disposition:" + base64String, Encoding.UTF8, "multipart/form-data");
var response = httpClient.SendAsync(request).Result;
}
}
}
i need to know how i can send the file in the body of the request what to write in this line
request.Content = new StringContent("Content-Disposition:" + base64String, Encoding.UTF8, "multipart/form-data");
pf is the posted file
then use
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AppUserContext.Token);
client.DefaultRequestHeaders.Add("x-language", "ar");
using (var stream = pf.InputStream)
{
var content = new MultipartFormDataContent();
var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result);
file_content.Headers.ContentType = new MediaTypeHeaderValue(pf.ContentType);
file_content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = JsonConvert.SerializeObject(pf.FileName),
};
content.Add(file_content);
var url = "URL Here";
var response = client.PostAsync(url, content).Result;
response.EnsureSuccessStatusCode();
}
}

Uploaded file always with size zero

I am trying to upload the file to web API so I have the following code
public async Task<Token> upload(string fullMd5, IEnumerable<HttpPostedFileBase> files)
{
string uploadUrl = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// Call CMS API
string jsonContent = string.Empty;
HttpClientHandler handler = new HttpClientHandler();
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
var filesData = new MultipartFormDataContent();
foreach (var item in files)
{
HttpContent filecontent = new StreamContent(item.InputStream);
filecontent.Headers.ContentType = new MediaTypeHeaderValue(item.ContentType);
filecontent.Headers.ContentLength += item.InputStream.Length;
filecontent.Headers.ContentDisposition = new ContentDispositionHeaderValue("multipart/form-data")
{
Name = "file",
FileName = item.FileName,
};
content.Add(filecontent);
}
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + userObj.access_token);
client.DefaultRequestHeaders.Add("Api-version", "2.4");
client.DefaultRequestHeaders.Add("CMSId", UserId);
var response = await client.PostAsync(uploadUrl, content);
jsonContent = await response.Content.ReadAsStringAsync();
}
}
var result = JsonConvert.DeserializeObject<Token>(jsonContent);
return result;
}
}
the API receive the files but corrupted with zero size , the API works well as I tested using postman , I tried to save the files before sending using SaveAs and it worked well any problem in how I send the file
Try using postAsync like this with these headers
using (var client = new HttpClient(handler) {BaseAddress = new Uri(_host)})
{
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(fileInfo.OpenRead());
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
Name = "\"file\"",
FileName = "\"" + fileInfo.Name + "\""
};
fileContent.Headers.ContentType =
MediaTypeHeaderValue.Parse(MimeMapping.GetMimeMapping(fileInfo.Name));
var folderContent = new StringContent(folderId.ToString(CultureInfo.InvariantCulture));
requestContent.Add(fileContent);
requestContent.Add(folderContent, "\"folderId\"");
var result = client.PostAsync("Company/AddFile", requestContent).Result;
}

How to Solve Azure DataLakeStore File Content-Disposition Added in file?

I was Uploaded Text file or image file or Zip File to Azure Data Lake Store. it' was Uploaded Successfully. But, before added some content in file.
I was Uploaded a File using Rest API. (Uploaded file using HttpClient in C#)
this Type of Content Added in
---b8b2dfc6-6128-43b5-8fb8-022820aedf02
Content-Disposition: form-data;
name=file1; filename=tick.txt; filename*=utf-8''tick.txt
If the Content Added So, The Image file and zip files are Not Open in Viewer/Explore.
How To Remove this type of header added in file From Upload.Here I shared my file uploaded code.
public object UploadFile(string srcfile, string destFilePath, bool force = true)
{
var uploadurl = string.Format(UploadUrl, _datalakeAccountName, destFilePath);
var stream = File.OpenRead(srcfile);
HttpContent fileStreamContent = new StreamContent(stream);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accesstoken.access_token);
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileStreamContent, "file1", Path.GetFileName(srcfile));
var response = client.PutAsync(uploadurl, formData).Result;
return new { Status = response.StatusCode, Message = response.ReasonPhrase, details = response.ToString() };
}
}
}
Thanks in Advance.
Please have try to use the following code, it works correcly on my side.
public object UploadFile(string srcfile, string destFilePath, bool force = true)
{
var uploadurl = string.Format(UploadUrl, _datalakeAccountName, destFilePath);
var stream = File.OpenRead(srcfile);
HttpContent fileStreamContent = new StreamContent(stream);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue("Bearer", _accesstoken.access_token);
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
var response = client.PutAsync(uploadurl, fileStreamContent).Result;
return new { Status = response.StatusCode, Message = response.ReasonPhrase, details = response.ToString() };
}
}

Categories

Resources