google drive sdk upload file - api

I tried to upload file, but then file is called "untitle".
byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);
string UploadURI = String.Format("https://www.googleapis.com/upload/drive/v2/files?uploadType=media&access_token={0}", accessToken);
var request = (HttpWebRequest)HttpWebRequest.Create(UploadURI);
request.Method = "POST";
request.ContentLength = fileBytes.Length;
using (var dataStream = request.GetRequestStream())
{
dataStream.Write(fileBytes, 0, fileBytes.Length);
}
string status = (((HttpWebResponse)request.GetResponse()).StatusDescription);
if (status.ToLower() == "created" || status.ToLower()=="ok")
{
Uploaded = true;
}
And how can I upload a file into a specific folder?

The answer to both the "untitle" and "parent folder" questions is the same. Meta Data. When you POST you should provide a meta data object containing a title:"title" and parents: [{id:"parent_id"}]

Related

Attaching files to Azure DevOps work item

I am trying to attach files (screenshots) to an Azure DevOps work item via a C# desktop app. I have managed to attach files, but they're not valid image files, which leads me to believe that I'm doing something wrong in uploading them.
From the documentation DevOps Create Attachment below is the section on the Request body of the API call, which is rather vague.
From a GitHub discussion this answer seems to suggest that I just upload the binary content directly, which is what I'm doing.
My code is as follows
var img = File.ReadAllBytes(fname);
string query = #"/_apis/wit/attachments?fileName=" + fname + #"&api-version=6.0"
string response = AzureUtils.AttachFile(query, img, "POST", false, "application/octet-stream");
Is it correct that I literally pass in the byte array which is read from the file (variable img) as the body?
Why is it not a valid file when I look at it in DevOps?
The code for AttachFile is
public static string AttachFile(string query, byte[] data = null, string method = "GET",
bool dontUseBaseURL = false, string contentType = "application/json-patch+json")
{
try
{
HttpWebRequest request = WebRequest.Create(query) as HttpWebRequest;
request.ContentType = contentType;
request.Method = method;
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Headers.Add("Authorization", "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{1}", ["AzurePAT"]))));
if (data != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
request = null;
response = null;
return result;
}

Sending PDF base64 using POST web request

I have a task which I need to upload a pdf converted to base64 string to Http post. I tried it using refit before but I failed to upload it. Now, I am trying a difference approach.
I used the web request POST method, First I converted the PDF to base64 but on the part that I call the stream.write method, I'm having an error since the file is already converted to base64 string and the stream.write paramater is byte array.
Also, how can I add these to the body using web request?
"mime": "application/pdf",
"data": "base64-data="
string pdfBase64;
const string pdfFileName = "file.pdf";
using (var pdfStream = await FileSystem.OpenAppPackageFileAsync(pdfFileName))
{
using (var pdfReader = new StreamReader(pdfStream))
{
var fileContents = await pdfReader.ReadToEndAsync();
pdfBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(fileContents));
}
}
WebRequest request = WebRequest.Create("https://goodmorning-axa-dev.azure-api.net/upload");
request.Method = "POST";
request.ContentLength = pdfBase64.Length;
request.ContentType = "application/json";
request.Headers.Add("x-axa-api-key", apiKey);
Stream stream = request.GetRequestStream();
stream.Write(pdfBase64, 0, pdfBase64.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
Toast.MakeText(this, sr.ReadToEnd(), ToastLength.Short).Show();
sr.Close();
stream.Close();

HttpWebRequest does not retrieve the url I have set for

I am trying to download
"https://www.google.com/search?sclient=psy-ab&biw=1472&bih=740&espv=2&tbm=vid&btnG=Search&q=%25%25%25#q=iran&tbm=nws";
by the following code:
string url = "https://www.google.com/search?sclient=psy-ab&biw=1472&bih=740&espv=2&tbm=vid&btnG=Search&q=%25%25%25#q=iran&tbm=nws";
try
{
string htmlPage = "";
//http request preparing
CookieContainer CC = new CookieContainer();
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Timeout = 60000;
objRequest.Proxy = null;
objRequest.UseDefaultCredentials = true;
objRequest.KeepAlive = false; //THIS DOES THE TRICK
objRequest.ProtocolVersion = HttpVersion.Version10; // THIS DOES THE TRICK
objRequest.CookieContainer = CC;
//http request sending
using (HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse())
{
using (Stream strm = objResponse.GetResponseStream())
{
using (StreamReader objStreamReader = new StreamReader(strm))
{
htmlPage = objStreamReader.ReadToEnd();
}
}
};
if (htmlPage.Contains("No results found for") || htmlPage.Contains("(without quotes):") || htmlPage.Contains("Make sure all words are spelled correctly."))
{
return dtResult;
}
else
{
Regex objEgEx = new Regex(#"[\r\n][ ]+\.[\r\n][ ]+");
htmlPage = objEgEx.Replace(htmlPage, string.Empty);
int startIndex = htmlPage.IndexOf("<div class =\"g\">");
if (startIndex == -1)
{ Console.Write("problem in parsing"); }
but HttpWebRequest download the first page of the google instead of the url I hd saved for it which is the address of the video search service of Google results' page.
what should I change so that it download the url I want?
You are downloading the page, not the query. Due that the search of google doesn't load a new page but updates a page. Maybe have a look into google search api

download doc file in MVC

I have applicaiton which is the combination of MVC 4 + Web Api + SQL server.
I am trying to download the doc file to MVC but i have tried the below step.
I have Web API where i have written the below code. when i send the rowid it has the value stored in the DB as varbinary. file format can be any thing like .doc,pdf etc ... but however I am looking for the first doc or PDF file format.
When I call the Web api it will create the PDF file and download it , but the file is completely corrupted.
[ResponseType(typeof(MandateExceptionDO))]
[HttpGet]
[Route("api/DealingMandate/GetExceptionDoc/{rowId}")]
public HttpResponseMessage GetExceptionDoc(int rowId)
{
IDealingMandates repository = new DealingMandatesRepository();
List<MandateExceptionDO> mandateexceptiondoc =new List<MandateExceptionDO>();
mandateexceptiondoc = repository.GetExceptionDoc(rowId);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
//response.Content = new ByteArrayContent(mandateexceptiondoc[0].Content);
//response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
//byte[] fileBytes = System.IO.File.ReadAllBytes(mandateexceptiondoc[0].Content);
response.Content = new ByteArrayContent(mandateexceptiondoc[0].Content);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "testing.pdf";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
//return Ok(mandateexceptiondoc);
return response;
}
I am able to fix this issue on the web api i made the byte as string as show below
String doc = Convert.ToBase64String(customermandate.Content);
and for the MVC side i converted back to byte from the string
var doc = restClient.Execute(request);
var response = doc.Content.Substring(1, doc.Content.Length - 2).Replace(#"\/", "/");
byte[] docBytes = Convert.FromBase64String(response);
if (doc.Content != null && doc.Content.Length > 0 && !string.IsNullOrEmpty(doc.Content))
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
Response.BinaryWrite(docBytes);
Response.End();
}

while uploading a file to dropbox getting an error with method

Am using below url to upload a file to dropbox using oauth and am getting an error
{"error": "Call requires one of the following methods: PUT, POST, got GET!"}
am passing httpmethod as PUT but still asking the error.
Signature am using to upload is
https://api-content.dropbox.com/1/files_put/dropbox/test?oauth_consumer_key=twcek2m7cxtantc&oauth_signature_method=PLAINTEXT&oauth_token=918v4lxg2w23car&oauth_version=1.0&oauth_signature=fbs34nykryouuj1%26rbbprgh95tjzf22
using this am getting the error
{"error": "Call requires one of the following methods: PUT, POST, got GET!"}
please tell me anyone what to do for resolve this error.
public FileSystemInfo UploadFile(string root, string path, string file)
{
var uri = new Uri(new Uri(DropboxRestApi.ApiContentServer),
String.Format("files_put/{0}/{1}",
root, UpperCaseUrlEncode(path)));
var oauth = new OAuth();
//var requestUri = oauth.DownloadSignRequest(uri, _consumerKey, _consumerSecret, "POST", _accessToken);
var requestUri = oauth.SignRequest(uri, _consumerKey, _consumerSecret, _accessToken, "PUT");
var request = (HttpWebRequest) WebRequest.Create(requestUri);
request.Method = WebRequestMethods.Http.Post;
request.KeepAlive = true;
byte[] buffer;
using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
int length = (int) fileStream.Length;
buffer = new byte[length];
fileStream.Read(buffer, 0, length);
}
request.ContentLength = buffer.Length;
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(buffer, 0, buffer.Length);
}
// request.Method = "POST";
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var json = reader.ReadToEnd();
return ParseJson<FileSystemInfo>(json);
}
I made a mistaken in saving path of the file where i want to upload it.
Give the same file name for save in path.
that's all.