I need to send file to WEB API using HttpClient and using the below code to achieve it. I couldn't figure out why am not revcieving any files in WEB API, but the request hits the APIcontroller.
Client Side Code
var fs = new FileStream(#"C:\SomLocation\ExcelFile.xlsx", FileMode.Open, FileAccess.Read);
MemoryStream ms = new MemoryStream();
fs.CopyTo(ms);
var client = new HttpClient();
client.BaseAddress = new Uri(GetAPIBaseAddress());
HttpContent content = new StreamContent(ms);
var data = new MultipartFormDataContent();
data.Add(content, "file1");
var response = client.PostAsync(GetImportAPIURL(), data).Result;
In API
System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
foreach(System.Web.HttpPostedFile file in hfc)
{
// do some processing;
}
Any help would be greatly appreciated.
Related
I'm trying to interact with a API that doesn't support multipart/form-data for uploading a file.
I've been able to get this to work with the older WebClient but since it's being deprecated I wanted to utilize the newer HttpClient.
The code I have for WebClient that works with this end point looks like this:
using (WebClient client = new WebClient())
{
byte[] file = File.ReadAllBytes(filePath);
client.Headers.Add("Authorization", apiKey);
client.Headers.Add("Content-Type", "application/pdf");
byte[] rawResponse = client.UploadData(uploadURI.ToString(), file);
string response = System.Text.Encoding.ASCII.GetString(rawResponse);
JsonDocument doc = JsonDocument.Parse(response);
return doc.RootElement.GetProperty("documentId").ToString();
}
I've not found a way to get an equivalent upload to work with HttpClient since it seems to always use multipart.
I think it would look something like this
using var client = new HttpClient();
var file = File.ReadAllBytes(filePath);
var content = new ByteArrayContent(file);
content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
var result = await client.PostAsync(uploadURI.ToString(), content);
result.EnsureSuccessStatusCode();
var response = await result.Content.ReadAsStringAsync();
var doc = JsonDocument.Parse(response);
return doc.RootElement.GetProperty("documentId").ToString();
What speaks against using simply HttpClient's PostAsync method in conjunction with ByteArrayContent?
byte[] fileData = ...;
var payload = new ByteArrayContent(fileData);
payload.Headers.Add("Content-Type", "application/pdf");
myHttpClient.PostAsync(uploadURI, payload);
I am trying to upload a document to Microsoft Teams using Microsoft Graph (beta version), but the document gets corrupted after a successful upload.
Using Graph, I'm first creating an Group, creating a Team based on the Group, adding some Team Members and finally uploading a document to the default channel.
All works fine except the uploaded document gets corrupted and the Office Online editor is not able to open it. We can however download the file and open in Microsoft Word after correcting the file.
Below is the code that I'm using for document upload->
FileInfo fileInfo =
new FileInfo(#"F:\Projects\TestProjects\MSTeamsSample\MSTeamsSample\Files\Test File.docx");
var bytes = System.IO.File.ReadAllBytes(fileInfo.FullName);
var endpoint = $"https://graph.microsoft.com/beta/groups/{groupId}/drive/items/root:/General/{fileInfo.Name}:/content";
var fileContent = new ByteArrayContent(bytes);
fileContent.Headers.ContentType =
MediaTypeHeaderValue.Parse("application/octet-stream");
var requestContent = new MultipartFormDataContent();
requestContent.Add(fileContent, "File", fileInfo.Name);
var request = new HttpRequestMessage(HttpMethod.Put, endpoint);
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", "<Access Token>");
request.Content = requestContent;
var client = new HttpClient();
var response = client.SendAsync(request).Result;
I tried changing content type to application/vnd.openxmlformats-officedocument.wordprocessingml.document but no luck. I don't understand what could be wrong here. The code is pretty straight forward, based on the this documentation. Any help will be highly appreciated.
Please try this:
var filePath = #"F:\Projects\TestProjects\MSTeamsSample\MSTeamsSample\Files\Test File.docx";
var fileName = Path.GetFileName(filePath);
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var endpoint = $"https://graph.microsoft.com/beta/groups/{groupId}/drive/items/root:/General/{fileName}:/content";
using (var client = new HttpClient())
{
using (var content = new StreamContent(fileStream))
{
content.Headers.Add("Content-Type", MimeMapping.GetMimeMapping(fileName));
// Construct the PUT message towards the webservice
using (var request = new HttpRequestMessage(HttpMethod.Put, endpoint))
{
request.Content = content;
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.Token);
// Request the response from the webservice
using (var response = await client.SendAsync(request))
{
// Check the response.
}
}
}
}
I am able to see Word document in Microsoft Teams editor.
I am trying to upload a file to Onedrive using RestSharp and Graph API. Basically I want to upload an Excel file. However, even the file saves, there is problem with the content. I am using:
https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_uploadcontent
using the code:
string newToken = "bearer ourtoken";
var client = new RestClient("https://xxx-my.sharepoint.com/_api/v2.0/"+ oneDrivePath + Path.GetFileName(filePathWithName) + ":/content");
var request = new RestRequest(Method.PUT);
request.RequestFormat = DataFormat.Json;
request.AddHeader("Authorization", newToken);
request.AddHeader("Content-Type", "text/plain");
byte[] sContents;
FileInfo fi = new FileInfo(filePathWithName);
// Disk
FileStream fs = new FileStream(filePathWithName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
sContents = br.ReadBytes((int)fi.Length);
br.Close();
fs.Close();
request.AddBody(Convert.ToBase64String(sContents));
var response = client.Execute(request);
This uploads the file however the XLSX file becomes corrupted.
Basically I need to figure out how to pass the stream to the RestSharp request.
Solved it by changing RestClient to HttpClient.
string newToken = "bearer mytoken"
using (var client = new HttpClient())
{
var url = "https://xxx-my.sharepoint.com/_api/v2.0/" + oneDrivePath + Path.GetFileName(filePathWithName) + ":/content";
client.DefaultRequestHeaders.Add("Authorization", newToken);
byte[] sContents = File.ReadAllBytes(filePathWithName);
var content = new ByteArrayContent(sContents);
var response = client.PutAsync(url, content).Result;
return response;
}
I'm a little confused about how to properly deserialize gziped Json payload from a HttpClient instance.
So far I'm doing the following, but it seems wrong. At least too complicated. Can't I feed a stream to Jil? Can't the HttpClient unzip the stream?
var client = new HttpClient();
var userEndPoint = new Uri(baseUri, "api/login");
var request = new HttpRequestMessage();
request.RequestUri = userEndPoint;
request.Method = HttpMethod.Get;
var response = _client.SendAsync(request).Result;
var userGzipByteArray = response.Content.ReadAsByteArrayAsync().Result;
var outStream = new MemoryStream();
using (var gzStream = new GZipStream(userGzipByteArray , CompressionMode.Decompress))
{
gzStream.CopyTo(outStream);
}
var userByteArray = outStream.ToArray();
var userJson = userByteArray .ConvertToString();
var user = JSON.Deserialize<User>(userJson , Jil.Options.ISO8601PrettyPrintIncludeInherited);
You can use the AutomaticDecompression flag for this. See Does .NET's HttpWebResponse uncompress automatically GZiped and Deflated responses?
I'm trying to post an image to my server using httpclient on Monodroid.
The server-code is ok, infact using Postman all goes well.
This is my code:
var req = new HttpRequestMessage (System.Net.Http.HttpMethod.Post, "http://192.168.0.50:2345/homo");
var content = new MultipartFormDataContent ();
var imageContent = new StreamContent (new FileStream ("my_path.jpg", FileMode.Open, FileAccess.Read, FileShare.Read));
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse ("image/jpeg");
content.Add (imageContent, "image", "image.jpg");
req.Content = content;
await client.SendAsync (req);
When I execute this code, on the server side I get this image:
So, like you can see, something comes... but it is not the complete file.
Can you help me?
Thanks a lot!
HttpClient buffers 64k, which probably equals to the data that is shown on the other side. To have it send the file in chunks do something like:
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.TransferEncodingChunked = true;
var content = new MultipartFormDataContent ();
var imageContent = new StreamContent (new FileStream ("my_path.jpg", FileMode.Open, FileAccess.Read, FileShare.Read));
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse ("image/jpeg");
content.Add(imageContent, "image", "image.jpg");
await httpClient.PostAsync(url, content);
However, you don't need the multipart if you are only sending one image...