File uploading not working on Win phone 8 - c#

I have a app in which user can record video and an api to upload recorded video to azure.
I am using below code
HttpClientHandler handler = new HttpClientHandler();
handler.MaxRequestContentBufferSize = int.MaxValue;
using (HttpClient httpClient = new HttpClient(handler)
{
MaxResponseContentBufferSize = int.MaxValue
})
{
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new ByteArrayContent(chunks), "file", fileName);
HttpResponseMessage response = null;
response = await httpClient.PostAsync(new Uri(url), content);
return await response.Content.ReadAsStringAsync();
}
This is working only when video is less than of 10 sec. When I tried to upload video of size around 20-30 MB than it fails.
In response I got status code 404.
I also tried another way to upload. But result was same error:
string boundary = Guid.NewGuid().ToString();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/form-data;boundary=" + boundary;
StringBuilder header = new StringBuilder();
header.Append("\r\n--");
header.Append(boundary);
header.Append("\r\n");
header.Append("Content-Disposition: file; name=\"file\"; filename=\"" + fileName + "\"\r\n");
header.Append("Content-Type: application/octet-stream\r\n\r\n");
byte[] headerbytes = Encoding.UTF8.GetBytes(header.ToString());
StringBuilder footer = new StringBuilder();
footer.Append("\r\n--");
footer.Append(boundary);
footer.Append("--\r\n");
byte[] footerbytes = Encoding.UTF8.GetBytes(footer.ToString());
using (var streamWriter = await request.GetRequestStreamAsync())
{
streamWriter.Write(headerbytes, 0, headerbytes.Length);
streamWriter.Write(footerbytes, 0, footerbytes.Length);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)await request.GetResponseAsync();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
return streamReader.ReadToEnd();
}

Check the web.config of your web.api site, in particular this section
<configuration>
<system.web>
<httpRuntime maxRequestLength="xxx" />
</system.web>
</configuration>
The xxx is in KB.

Related

c # desktop app error 401 How can I send the data

I do not have a problem getting tokens in the desktop application I developed. But when I try to send data, I get a 401 error.
HttpWebRequest webRequest;
string requestParams = "";
webRequest = (HttpWebRequest)WebRequest.Create("url");
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Headers.Add("x-api-key", "112233");
webRequest.Headers.Add("AccessToken", token);
byte[] byteArray = Encoding.UTF8.GetBytes(req);
webRequest.ContentLength = byteArray.Length;
using (Stream requestStream = webRequest.GetRequestStream())
{
requestStream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = webRequest.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
StreamReader rdr = new StreamReader(responseStream, Encoding.UTF8);
string Json = rdr.ReadToEnd();
}
}
The problem is about setting the token. First, you need to be sure what your server wants as a token. You can try this for the Bearer token.
webRequest.Headers.Add("Authorization", "Bearer " + token);
For your program to work, you have to provide an actual URL, not just the string "url", in
webRequest = (HttpWebRequest)WebRequest.Create("url");
Post to api with c # windows form application. oauth2.0
using (var client1 = new HttpClient ())
{
client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token());
client1.DefaultRequestHeaders.Add("x-api-key", "xxxx");
var builder = new UriBuilder(new Uri("you - url"));
HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Post, builder.Uri);
request1.Content = new StringContent("{\"values\":" + JsonConvert.SerializeObject("you -data")+ "}", Encoding.UTF8, "application/json");
HttpResponseMessage response = await client1.SendAsync(request1);
};

C# Binary File Post Request

I am dealing with a third-party API which insists on a binary File Upload request being formatted without a Content-Type header value of multipart/form-data, and with the following headers:
Content-Type: application/octet-stream
Content-Disposition: filename*=UTF-8''file.zip
HttpRequestMessage and HttpContent.Headers.ContentDisposition.DispositionType won't allow me to achieve this either because I can't set the values as desired or they set them automatically.
I accept that this API may not be following HTTP Standards but it's not mine and I have no influence over it.
My attempt which does not work
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.ExpectContinue = false;
FileStream fs = new FileStream(#"e:\dev\TestHalfB.docx", FileMode.Open);
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, <Uri>);
HttpContent fc = new StreamContent(fs);
var mpContent = new MultipartFormDataContent();
mpContent.Add(fc);
fc.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
req.Content = fc;
fc.Headers.ContentDisposition.DispositionType = "filename*=UTF-8''TestHalfB.docx";
using (var response = await client.SendAsync(req))
{
response.EnsureSuccessStatusCode();
var resp = await response.Content.ReadAsStringAsync();
}
fs.Close();
}
Does anyone know of a lower level API I could use or have any suggestions?
So the crux is how can I set the Content-Disposition header to the value I desire.
I had to switch to using WebRequest.
WebRequest request = WebRequest.Create("https://cloud.memsource.com/web/api2/v1/projects/{id}/jobs?token={token}");
request.Method = "POST";
byte[] byteArray = File.ReadAllBytes(#"E:\Dev\TestHalfB.docx");
request.ContentType = "application/octet-stream";
request.ContentLength = byteArray.Length;
request.Headers.Add("Content-Disposition", "filename*=UTF-8''TestHalfB.docx");
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
((HttpWebResponse)response).StatusDescription.Dump();
Could you please try this.
HttpContent fileStreamContent = new StreamContent(paramFileStream);
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileStreamContent, "file1", "file1");
var response = client.PostAsync(actionUrl, formData).Result;
}
This should work for you (or at least get you started, since it's not tested):
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, <Uri>);
using (FileStream fs = new FileStream(#"e:\dev\TestHalfB.docx", FileMode.Open))
{
byte[] fb = new byte[(int)fs.Length]; // assumes your file size will fit into an int
await fs.ReadAsync(fb, 0, (int)fs.Length);
req.Content = new ByteArrayContent(fb);
req.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
req.Content.Headers.ContentDisposition.FileNameStar = "UTF-8''TestHalfB.docx";
using (var response = await client.SendAsync(req))
{
response.EnsureSuccessStatusCode();
var resp = await response.Content.ReadAsStringAsync();
}
}

Upload to Onedrive with C# using Graph API

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

c# Dropbox RestSharp download file to stream

I have an 'ASP.NET' console application and I use 'RestSharp' client for Dropbox.
I use this code to download a file :
var baseUrl = "https://content.dropboxapi.com";
var client = new RestClient(baseUrl);
client.Authenticator = OAuth1Authenticator.ForRequestToken(mc_apiKey, mc_appsecret);
RestRequest request = new RestRequest(string.Format("/{0}/files/auto", mc_version), Method.GET);
client.Authenticator = OAuth1Authenticator.ForProtectedResource(mc_apiKey, mc_appsecret, accessToken.Token, accessToken.Secret);
request.AddParameter("path", path);
var responseAccount = client.Execute(request);
var fileString = responseAccount.Content;
byte[] b1 = System.Text.Encoding.UTF8.GetBytes (fileString);
When call client.Execute(request)the whole file is loaded in memory, so when I have a very largefile in Dropbox the program will crash.
I need to get the file to stream without using client.DownloadData(request).SaveAs(path) to download to local storage.
I need to be able to stream the file in chunks.
You can set the request.ResponseWriter like so :
var baseUrl = "https://content.dropboxapi.com";
var client = new RestClient(baseUrl);
client.Authenticator = OAuth1Authenticator.ForRequestToken(mc_apiKey,mc_appsecret);
RestRequest request = new RestRequest(string.Format("/{0}/files/auto", mc_version), Method.GET);
client.Authenticator = OAuth1Authenticator.ForProtectedResource(mc_apiKey, mc_appsecret, accessToken.Token, accessToken.Secret);
request.AddParameter("path", path);
string tempFile = Path.GetTempFileName();
using(var stream = File.Create(tempFile, 1024, FileOptions.DeleteOnClose ))
{
request.ResponseWriter = (responseStream) => responseStream.CopyTo(stream);
var response = client.DownloadData(request);
}
You can see the example from the docs here
I found the best answer in link:
string url = String.Format("https://content.dropboxapi.com/1/files/auto{0}?oauth_consumer_key={1}&oauth_token={2}&oauth_signature={3}%26{4}", path, app-key, access-token, app-secret, access-token-secret);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "Get";
WebResponse webResponse = null;
try
{
webResponse = webRequest.GetResponse();
return webResponse.GetResponseStream();
}
catch (Exception ex)
{
throw ex;
}

How to create folder and upload file using Rest api and oauth2.0

I want to create a folder and upload files using rest api
my code is like this
public string CreateFolder(string FolderName)
{
int WorkSpaceId = 330201;
int id = 168079105;
var queryString = HttpContext.Current.Session["tokenSession"];
var request = WebRequest.Create(RequestProfileUrl + FolderName);
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
request.Headers.Add("Authorization", "Bearer " + AccessToken);
request.ContentType = "multipart/form-data";
request.Method = "POST";
var response = request.GetResponse();
HttpContext.Current.Response.Redirect("" + request.RequestUri);
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
var responseText = reader.ReadToEnd();
reader.Close();
return responseText;
}
}
I have to do like this
POST https://apis.live.net/v5.0/me/skydrive
Authorization: Bearer ACCESS_TOKEN
Content-Type: multipart/form-data
{
"name": "My example folder"
}`
I added request header and content-type, I don't know how to add name parameter to my request.
To write the body of your POST request you need to get the request stream first, and then write to it. See the sample code below. Note that I changed the Content-Type from "multipart/form-data" to "application/json" as this is what your data seems to be.
// String with the body content
string postBody = "{\"name\":\"myfoldername\"}";
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postBody);
// Set Content type to application/json
myHttpWebRequest.ContentType = "application/json";
// Set content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;
// Get the request stream and write body bytes to it
Stream newStream = myHttpWebRequest.GetRequestStream ();
newStream.Write (byte1, 0, byte1.Length);

Categories