Empty attachement through post WS - c#

I'am trying to send attachement to atlassain Jira, but my files are empty.
string postUrl = url + "/rest/api/2/issue/" + issuekey + "/attachments";
MultipartFormDataContent content = new MultipartFormDataContent();
client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");
HttpContent fileContent1 = new ByteArrayContent(Convert.FromBase64String(docbody));
content.Add(fileContent1, "file", filename);
var response2 = client.PostAsync(postUrl, content).Result;
if (response2.IsSuccessStatusCode)
{
Console.WriteLine("OK");
}

Related

How to convert WebClient to HttpClient C# WinForms

I need to convert the webclient code which is obsolte to httpclient.
using WebClient Client = new();
Client.Headers["User-Agent"] = CompanyName + "/" + ProductName;
byte[] responseBytes = Client.UploadFile("http://blahblah.com/upload.php", fileimage);
string response = Encoding.Default.GetString(responseBytes);
_ = MessageBox.Show(response, Text);
I need the exact same way to do this. I have seen other answers but none meet my needs.
1- read AllByte of file into upfilebytes array
2-create new HttpClient and MultipartFormDataContent
3- add byte array to content
4-upload MultipartFormDataContent content async and store response in response.
var upfilebytes = File.ReadAllBytes("fileimage");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("User-Agent", CompanyName + "/" + ProductName);
MultipartFormDataContent content = new MultipartFormDataContent();
ByteArrayContent baContent = new ByteArrayContent(upfilebytes);
content.Add(baContent, "File", "filename.png");
var response = await client.PostAsync("http://blahblah.com/upload.php", content);
var responsestr = await response.Content.ReadAsStringAsync();
MessageBox.Show(response, responsestr);
The simplest way you can upload a file is something like here.However,
it's better to use HttpClientFactory to generate httpclient instance.
var client = new HttpClient
{
BaseAddress = new("http://blahblah.com/upload.php")
};
await using var stream = System.IO.File.OpenRead("filePathHere");
using var request = new HttpRequestMessage(HttpMethod.Post, "file");
request.Headers.Add("User-Agent",CompanyName + "/" + ProductName);
using var content = new MultipartFormDataContent
{
{ new StreamContent(stream), "file", "fileNameHere" }
};
request.Content = content;
var response = await client.SendAsync(request);
MessageBox.Show(response, Text);

Translate single document using azure translator

I want to translate single document from one language to another please guide me how to do that i have done translating all the files in azure blob storage but not able to find to translate single file.
please find below code and let me know the changes.
string _FileName = Path.GetFileName(file.FileName);
fileName = _FileName;
string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
file.SaveAs(_path);
string route = "/batches";
string endpoint = "https://translator.cognitiveservices.azure.com/translator/text/batch/v1.0";
string filePath = UploadToAzureStorageAccount.UploadDocument(_path, "uploadeddocs");
string subscriptionKey = "key";
string json = ("" +
"{\"inputs\": " +
"[{\"storageType\": \"File\","+"\"source\": " +
"{\"sourceUrl\": \"https://cdposticketsstorage.blob.core.windows.net/uploadeddocs/test.docx?sp=r&st=2022-03-08T08:13:18Z&se=2022-03-08T16:13:18Z&spr=https&sv=2020-08-04&sr=b&sig=Pt68ogFCj6WSgEBUWI95YJ4GudOcyhEW1cgVXmFCing%3D\"," +
"\"storageSource\": \"AzureBlob\"" +
"}," +
"\"targets\": " +
"[{\"targetUrl\": \"https://cdposticketsstorage.blob.core.windows.net/translateddocs/translate.docx?sp=rcw&st=2022-03-08T11:15:45Z&se=2022-03-08T19:15:45Z&spr=https&sv=2020-08-04&sr=b&sig=QM2FhLxOIE%2FLjeLLfYyR2PmfkNb3nm70wZdCveSJC0M%3D\"," +
"\"storageSource\": \"AzureBlob\"," +
"\"language\": \"fr\"}]}]}");
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
string result = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Status code: {response.StatusCode}");
Console.WriteLine();
Console.WriteLine($"Response Headers:");
Console.WriteLine(response.Headers);
}
else
Console.Write("Error");
}
// TextTranslatorAPI client = new TextTranslatorAPI();
//string res = await client.DocumentTranslator(fileName);
//return res;
}
ViewBag.Message = "File Uploaded Successfully!!";
}
catch(Exception e)
{
ViewBag.Message = "File upload failed!!";
}

POST result empty after passing a JSON string along with a file

I'm encountering an issue uploading a file (image for this example) along with a JSON string. I am as the client, trying to upload to a webserver. Currently on the website itself, when uploading a file, the payload is this:
------WebKitFormBoundary1A4Toq4hnrayCRu4
Content-Disposition: form-data; name="FileInstance"
{"action":["/public/my_folder"],"fileName":"download_icon.png","fileSize":313,"certification":{"level":"0","Groups":[]}}
------WebKitFormBoundary1A4Toq4hnrayCRu4
Content-Disposition: form-data; name="download_icon.png"; filename="download_icon.png"
Content-Type: image/png
------WebKitFormBoundary1A4Toq4hnrayCRu4--
I am POSTing by 2 separate requests, and each result has a 200 status code, but looking into the result, it's empty and I should be receiving an md5hash of the file uploaded but I am not.
Here is my code:
// Uploading the JSON first
MultipartFormDataContent form = new MultipartFormDataContent();
var boundary = $"----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
form.Headers.Remove("Content-Type");
form.Headers.Add("Content-Type", $"multipart/form-data; boundary={boundary}");
MyFileClass currentFile = new MyFileClass();
currentFile.action = new List<string>() { "/public/my_folder" };
currentFile.filename = Path.GetFileName(Filename);
currentFile.fileSize = Convert.ToInt32(new FileInfo(Filename).Length);
currentFile.certification= new MyFileClass.Certification();
CreateCertification(currentFile.certification);
var json = JsonConvert.SerializeObject(currentFile);
HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = Path.GetFileName(Filename),
FileName = Path.GetFileName(Filename)
};
var response = await myHttpClient.PostAsync(url, form);
var result_str = response.Content.ReadAsStringAsync().Result;
// Uploading the actual file
var stream = new FileStream(Filename, FileMode.Open);
form = new MultipartFormDataContent();
boundary = $"----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");
form.Headers.Remove("Content-Type");
form.Headers.Add("Content-Type", $"multipart/form-data; boundary={boundary}");
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "FileInstance"
};
content = new StreamContent(stream);
form.Add(content, Path.GetFileNameWithoutExtension(Filename));
response = await myHttpClient.PostAsync(url, form);
result_str = response.Content.ReadAsStringAsync().Result;
Edit 1: This is how httpclient is defined:
string password = SecureStringExtensions.ToUnsecuredString(Password);
var credCache = new CredentialCache
{
{
new Uri(url), "Basic", new NetworkCredential(Username, password)
}
};
var myHttpClient = new HttpClient(new HttpClientHandler() { Credentials = credCache });
myHttpClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
myHttpClient.Timeout = Timeout.InfiniteTimeSpan;
I was trying different methods of POSTing which didn't work. Now I found a solution, where I removed editing the boundary and ContentType, and straight forward added the file and JSON at the same time to MultipartFormDataContent and it worked fine.
MyFileClass currentFile = new MyFileClass();
currentFile.action = new List<string>() { "/public/my_folder" };
currentFile.filename = Path.GetFileName(Filename);
currentFile.fileSize = Convert.ToInt32(new FileInfo(Filename).Length);
currentFile.certification= new MyFileClass.Certification();
CreateCertification(currentFile.certification);
var json = JsonConvert.SerializeObject(currentFile);
var formContent = new MultipartFormDataContent
{
{ new StringContent(json, Encoding.UTF8, "application/json") },
{ new StreamContent(new MemoryStream(File.ReadAllBytes(Filename))), Path.GetFileName(Filename) ,Path.GetFileName(Filename)}
};
var response = await myHttpClient.PostAsync(url, formContent);
string stringContent = await response.Content.ReadAsStringAsync();
Where Filename is the absolute path of the file itself.

Httpclient multipart/form-data pust image

I am trying to send a Put request with binary file to upload to the server, using Httpclient.SendAsync or Httpclient.PutAsync. But all i got is 400 bad request in server response. Here is the code
private static HttpResponseMessage Upload()
{
var apiUri = string.Format(url);
string url = (url);
var message = new HttpRequestMessage();
message.RequestUri = new Uri(apiUri);
message.Method = HttpMethod.Put;
var fileObj = Images.ChooseImageAndToInfoObject();
using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
{
var filestream = new FileStream(fileObj.filePath, FileMode.Open);
content.Add(new StreamContent(filestream), fileObj.fileName, fileObj.fileNameWithExtension);
content.Add(new StringContent("file"), "withName");
content.Add(new StringContent("string"), "fileName");
content.Add(new StringContent("image/*"), "mimeType");
message.Content = content;
message.Headers.Add("Authorization", MyToken);
// var res = client.SendAsync(message).Result;
var response = client.PutAsync(url, content).Result;
return response;
}
Hope for you, guys
Is it necessary to send the filename and mimetype via multipart-formdata? If not try to send the data as StreamContent and set the filename and mime type via the content header:
private static HttpResponseMessage Upload()
{
var apiUri = string.Format(url);
string url = (url);
var message = new HttpRequestMessage();
message.RequestUri = new Uri(apiUri);
message.Method = HttpMethod.Put;
var fileObj = Images.ChooseImageAndToInfoObject();
using (var client = new HttpClient())
var filestream = new FileStream(fileObj.filePath, FileMode.Open);
var content = new StreamContent(filestream);
content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileObj.filePath));
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"files\"",
FileName = "\"" + fileName + "\""
};
message.Content = content;
message.Headers.Add("Authorization", MyToken);
// var res = client.SendAsync(message).Result;
var response = client.PutAsync(url, content).Result;
return response;
Send the content via PUT if you set the file to a specific id or via Post:
var response = client.PostAsync(url, content).Result;

Unable to get header "Content-Disposition" with httpclient in C#

SCENARIO:
First of all, please consider I'm using HttpClient class, not WebRequest, I know that there is a lot of related question here but all answers are for WebRequest.
I made a Web Api Application that set in this way the following header in order to download a .txt file:
resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
resp.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = _datacontext.GetAppConfig("814FileNameHeader") + DateTime.Now.ToString("yyyyMMdd") + ".txt"
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
After I made an HttpClient from other application to connect to this method.
Everything is working, retrieves 200 and the content of the file. But I can't get the header in order to read the filename.
TRIES MADE:
Working with a REST Client I can read the following header attribute:
Content-Disposition: attachment; filename=814Entes_PG_20160114.txt
and from the code I could debug it and I found that the header is in "invalidHeaders" but I can't reach the value:
QUESTION:
How can I set up this and getting without any doubt from the client?
UPDATE:
These are my tries to get the header:
The original:
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(uri);
string authentication = string.Concat(authenticationArgs[0], ":", authenticationArgs[1]);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + Base64Encode(authentication));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "Report/" + type);
req.Content = new StringContent("");
HttpResponseMessage response = await httpClient.SendAsync(req);
Console.WriteLine(response.StatusCode);
if (response.IsSuccessStatusCode)
{
string stream = response.Content.ReadAsStringAsync().Result;
Console.Write("Respuesta servicio: " + stream);
Console.WriteLine(stream);
string cp = response.Headers.GetValues("Content-Disposition").ToString();
}
The second one I tried with some SO investigation:
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(uri);
string authentication = string.Concat(authenticationArgs[0], ":", authenticationArgs[1]);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + Base64Encode(authentication));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "Report/" + type);
req.Content = new StringContent("");
HttpResponseMessage response = await httpClient.SendAsync(req);
Console.WriteLine(response.StatusCode);
if (response.IsSuccessStatusCode)
{
string stream = response.Content.ReadAsStringAsync().Result;
Console.Write("Respuesta servicio: " + stream);
Console.WriteLine(stream);
string cp = "";
HttpHeaders headers = response.Headers;
IEnumerable<string> values;
if (headers.TryGetValues("Content-Disposition", out values))
{
cp = values.ToString();
}
}
If you are trying to get the headers of the content, it should be from response.Content.Headers
As per #terbubbs you need response.Content.Headers.
But also code needs to be - for the first code sample:
string cp = response.Result.Content.Headers.GetValues("Content-Disposition").ToList()[0];
And for the second:
cp = values.FirstOrDefault().ToString();
Otherwise the result is System.String[]

Categories