Web service upload file errors - c#

I am uploading a file to a web service...the prootocol for the web service is like this :
HTTP POST request parameters “USERNAME” , “PASSWORD” and “FILE” is required.
Multipart form submission, i.e. use a FORM 'enctype' attribute of 'multipart/form-data', must be used.
and
the “&” character should be replaced by “%26”, and “ “ (space) replaced by “%20” when used to construct a URL.
I am referring to the post Upload files with HTTPWebrequest (multipart/form-data) to build this web request...
my code is as follows...
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
NameValueCollection nvc = new NameValueCollection();
nvc.Add("USERNAME", "myusernammeee");
// nvc.Add("PASSWORD", "mS89_n3w");
nvc.Add("PASSWORD", "mypasswordddd");
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate =
"Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "FILE", files[0], "xml");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
StringBuilder inFile = new StringBuilder(1000);
//First of all lets read the contents of the file in.
using (TextReader streamReader = new StreamReader(files[0]))
{
while (streamReader.Peek() >= 0)
{
inFile.Append(streamReader.ReadLine());
}
}
string inputFile = inFile.ToString().Replace("&", "%26amp;");
byte[] fileBytes = Encoding.UTF8.GetBytes(inputFile);
rs.Write(fileBytes,0, fileBytes.Length);
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
}
catch (Exception ex)
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
but when i do this I am getting an error "Bad Request". I am not sure what I am doing wrong here.. Any suggestion would be greatly appreciated.
Thanks

Related

Unable to upload file to salesforce using c#

I am using salesforce v49.0. I wrote code to upload file(txt file) from my directory to salesforce.
I have created a folder in my salesforce account.
I am getting Bad Request while trying to upload.
Please help to find the solution or suggest any other ways to upload the file.
My Code
string oauthToken = (string)loginResponse["access_token"];
string serviceUrl = (string)loginResponse["instance_url"];
var doc = new sfdcDocument();
doc.Name = "DocumentbyDuke";
doc.FolderId = "05He0000RE00CcKDERTD";
doc.Type = "txt";
doc.Keywords = "123";
doc.Description = "123";
string boundary = "----" + DateTime.Now.Ticks.ToString("x");
var uri = serviceUrl + "/services/data/v49.0/sobjects/Document/";
var req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
req.Headers.Add("Authorization: OAuth " + oauthToken);
req.ContentType = "multipart/form-data; boundary=" + boundary;
req.Method = "POST";
var os = req.GetRequestStream();
// Add header for JSON part
string body = "";
body += "\r\n--" + boundary + "\r\n"; ;
body += "Content-Disposition: form-data; name='entity_document'\r\n";
body += "Content-Type: application/json\r\n\r\n";
// Add document object data in JSON
body += JsonConvert.SerializeObject(doc);
// Add header for binary part
body += "\r\n--" + boundary + "\r\n"; ;
body += "Content-Disposition: form-data; name='Body'; filename='1.txt'\r\n";
body += "Content-Type: binary/octet-stream\r\n\r\n";
// Add header data to request
byte[] data = System.Text.Encoding.ASCII.GetBytes(body);
os.Write(data, 0, data.Length);
// Add file to reqeust
FileStream fileStream = new FileStream(#"C:\Users\AprilFile.txt", FileMode.Open, FileAccess.ReadWrite);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
os.Write(buffer, 0, bytesRead);
}
fileStream.Close();
// Add trailer
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
os.Write(trailer, 0, trailer.Length);
os.Close();
// Do the post and get the response.
WebResponse resp;
try
{
resp = req.GetResponse();
}
catch (WebException ex)
{
resp = ex.Response;
}
//if (resp == null) return null;
var sr = new System.IO.StreamReader(resp.GetResponseStream());
08H, as shown in your comment is not the Key Prefix for any type of Folder. It appears to belong to an obscure sObject called CleanBatchErrorLog.
05H corresponds to ContentDistributionView, which is also incorrect.
While there may be other issues, you definitely need to locate the correct folder id to store this document.

How to upload files from a .NET-Application to a Rocket.Chat-Channel?

I need to make a feedback-form in my .NET application, which sends messages to a Rocket.Chat-Channel (What is Rocket.Chat?).
I am already able to send a textmessage with the api of Rocket.Chat.
I found a documentation, how to send files with an api, but i never had done this before. How can I send the files with my Json?
Someone did that before? Maybe somebody can give me a small example to get this done.
This is the code of my method, which sends the textmessage.
private void SendToRocketChat()
{
var baseAddress = "https://plc.ifm-sw.net/api/v1/chat.sendMessage";
var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
http.Method = "POST";
http.ContentType = "application/json";
http.Headers.Add("X-Auth-Token", "4ZLqSyN9IEFIkj6SqIde2a4orHhEdL8S0eGPEFdfS9C");
http.Headers.Add("X-User-Id", "rocket.cat");
string rid = "F24Ydk2kkTXAPWsQ9";
JObject Json = new JObject(new JProperty("message", new JObject(new JProperty("rid", rid), new JProperty("msg", WebUtility.HtmlEncode(FeedbackText)))));
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(Json.ToString());
Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
logger.LogInformation(JsonConvert.DeserializeObject(content).ToString().Trim('{', '}'));
}
And this is what i already tried for the Fileupload. Where is my error?
private void SendFileToRocketChat()
{
var url = "https://example-sw.net/api/v1/rooms.upload/:gdfgfgdkTXAPWsQ9";
var filePath = "Abbildung13.jpg";
var httpClient = (HttpWebRequest)WebRequest.Create(new Uri(url));
httpClient.Method = "POST";
httpClient.Headers.Add("X-Auth-Token", "4ZLqSyN9IEhEdLgfd8S0eGPEFdfS9C");
httpClient.Headers.Add("X-User-Id", "rocket.cat");
httpClient.ContentType = "multipart/form-data";
MultipartFormDataContent form = new MultipartFormDataContent();
FileStream fs = File.OpenRead(filePath);
var streamContent = new StreamContent(fs);
var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(imageContent, "file", Path.GetFileName(filePath));
form.Add(imageContent, "msg", "This is a message with a file");
form.Add(imageContent, "description", "Simple text file");
var response = httpClient.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
logger.LogInformation(JsonConvert.DeserializeObject(content).ToString().Trim('{', '}'));
}
After some time i got a code, which is working fine. Maybe it will help someone later.
private void SendFileToRocketChat()
{
var url = "https://exampleurl.net/api/v1/rooms.upload/fsgfadgTXAPWsQ9";
var filePath = "text.zip";
NameValueCollection formFields = null;
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
request.Headers.Add("X-Auth-Token", "4ZLqSyN9IEgfasgfdagsdg8S0eGPEFdfS9C");
request.Headers.Add("X-User-Id", "rocket.bot");
Stream memStream = new System.IO.MemoryStream();
var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
string files = filePath;
if (formFields != null)
{
foreach (string key in formFields.Keys)
{
string formitem = string.Format(formdataTemplate, key, formFields[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
}
string headerTemplate = "Content-Disposition: form-data; name=\"file\"; filename=\"{1}\"\r\n" + "Content-Type: application/zip\r\n\r\n";
memStream.Write(boundarybytes, 0, boundarybytes.Length);
var header = string.Format(headerTemplate, "file", files);
var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
using (var fileStream = new FileStream(files, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[1024];
var bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
}
memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
request.ContentLength = memStream.Length;
using (Stream requestStream = request.GetRequestStream())
{
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
}
using (var response = request.GetResponse())
{
Stream stream2 = response.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
string res = reader2.ReadToEnd();
logger.LogInformation(JsonConvert.DeserializeObject(res).ToString().Trim('{', '}'));
}
}

How can I use the AtTask API to Upload a File using C#

I am using a modified version of the C# API Example to add tasks to an existing Workfront (AtTask) Task. I would also like to upload and download file attachments.
It appears from the documentation that uploading is a two-step process, step 1 upload the file and step 2 attach the uploaded file to the task. I understand somewhat how to do the second step - post a JSON token with the file name, the handle (from the upload), object type (TASK), object ID, and currentVersion. What I don't understand is step 1, the actual uploading of the file.
I am creating a PDF file that needs to be attached to the task. Once the task is completed, a new document will be added that I need to download.
Does anyone have any C# code for performing either the upload or the download?
Here is my code so far:
public JToken DoUpload(string path, string opportunityID, string description, params string[] parameters)
{
List<string> list = parameters.ToList();
if (!path.StartsWith("/"))
{
path = "/" + path;
}
string fullUrl = url + path + ToQueryString(parameters);
string boundary = "------" + DateTime.Now.Ticks.ToString("x");
WebRequest request = HttpWebRequest.CreateDefault(new Uri(fullUrl));
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
using (var requestStream = request.GetRequestStream())
{
using (var writer = new StreamWriter(requestStream))
{
writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\" filename=\"{1}\"", "uploadedFile", "RFQ" + opportunityID + ".html"));
writer.WriteLine("Content-Type: text/html; charset=UTF-8");
writer.WriteLine();
writer.WriteLine(description);
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
return ReadResponse(responseStream);
}
}
}
}
}
public static string HttpUploadFile(string url, string filename, byte[] file, string paramName, string contentType, NameValueCollection nvc)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, filename, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
rs.Write(file, 0, file.Length);
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
string ret = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
ret = reader2.ReadToEnd();
}
catch (Exception ex)
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
return ret;
}
JToken ret = HttpUploadFile("/upload", file_name, file_bytes, "uploadedFile", "", new NameValueCollection());
The first step is to get a handel, that is done just like any other api call you do to POST /attask/api/upload, this is where you include the file, it will be uploaded to a temp folder at Workfront(AtTask), Workfront will return the handel, then you do a second step to update the task incldue the handel and the file will be posted to it.
For more reference check out https://developers.attask.com/api-docs/ and https://developers.attask.com/api-docs/code-samples/

Upload a file using the HTTPWebrequest(does not pass, post data)

I Tries to upload a file using the HTTPWebrequest(multipart/form-data).
So I see a few pages, and wrote the following code :
var boundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes(boundary);
var template = boundary + "\r\n" +
"Content-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n" +
"{1}\r\n";
// Request Header
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://domain.com/test.php");
req.Method = "POST";
req.KeepAlive = true;
req.ContentType = "multipart/form-data; boundary=" + boundary;
req.CookieContainer = COOKIE;
Stream ms = new MemoryStream();
string formItem;
byte[] formItemBytes;
string fileName = Path.GetFileName(#"C:\Users\Username\Image.jpg");
// POST Data
formItem = string.Format(template, "Filename", fileName);
formItemBytes = Encoding.UTF8.GetBytes(formItem);
ms.Write(formItemBytes, 0, formItemBytes.Length);
formItem = string.Format(template, "Username", "RedPetals");
formItemBytes = Encoding.UTF8.GetBytes(formItem);
ms.Write(formItemBytes, 0, formItemBytes.Length);
var headerTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
string header = string.Format(headerTemplate, "Image", fileName);
byte[] headerBytes = Encoding.UTF8.GetBytes(header);
ms.Write(boundaryBytes, 0, boundaryBytes.Length);
ms.Write(headerBytes, 0, headerBytes.Length);
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
{
ms.Write(buffer, 0, bytesRead);
}
}
byte[] boundaryEndBytes = Encoding.ASCII.GetBytes(boundary + "--");
ms.Write(boundaryEndBytes, 0, boundaryEndBytes.Length);
req.ContentLength = ms.Length;
ms.Position = 0;
byte[] tempBuffer = new byte[ms.Length];
ms.Read(tempBuffer, 0, tempBuffer.Length);
ms.Close();
using(Stream rs = req.GetRequestStream())
{
rs.Write(tempBuffer, 0, tempBuffer.Length);
}
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string result = "";
if (response.StatusCode == HttpStatusCode.OK)
{
Stream resStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(resStream, Encoding.UTF8);
result = readStream.ReadToEnd();
Console.Write(result);
resStream.Close();
readStream.Close();
}
But does not pass POST data.. Is there a part I missed?
HttpAnalyzer Post 'Data'(Formdata tab is 'No data to display') :
----------8d1984e7dd49750
Content-Disposition: form-data; name="Filename"
Image.jpg
----------8d1984e7dd49750
Content-Disposition: form-data; name="Username"
RedPetals
----------8d1984e7dd49750
Content-Disposition: form-data; name="img"; filename="Image.jpg"
Content-Type: application/octet-stream
???
----------8d1984e7dd49750--
Response result :
// echo var_dump($_POST); echo var_dump($_FILES);
array(0) { } array(0) { }
Resolved
//var boundary = "----------" + DateTime.Now.Ticks.ToString("x");
var boundary = "--------" + DateTime.Now.Ticks.ToString("x");
// var template = boundary + "\r\n" +
// "Content-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n" +
// "{1}\r\n";
var template = "--" + boundary + "\r\n" +
"Content-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n" +
"{1}\r\n";
Here's my solution when I encountered this issue:
Client:
public async Task UploadImage(byte[] image, string url)
{
Stream stream = new System.IO.MemoryStream(image);
HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());
Uri resourceAddress = null;
Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress);
Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress);
request.Content = streamContent;
var httpClient = new Windows.Web.Http.HttpClient();
var cts = new CancellationTokenSource();
Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token);
}
Controller:
public async Task<HttpResponseMessage> Post()
{
Stream requestStream = await this.Request.Content.ReadAsStreamAsync();
byte[] byteArray = null;
using (MemoryStream ms = new MemoryStream())
{
await requestStream.CopyToAsync(ms);
byteArray = ms.ToArray();
}
.
.
.
return Request.CreateResponse(HttpStatusCode.OK);
}

Getting a 400 Bad Request error when uploading file to OneDrive through REST

I am trying to upload a file to OneDrive using REST but am seeing a 400 bad request error when I try to do so. This is my code:
//Where I call it
//fileLoc being C:\\path\\test.doc
HttpUploadFile("https://apis.live.net/v5.0/folder.xxxxxxxx/files/" + "?" + access_token, #fileLoc, "file", "application/octet-stream");
public static void HttpUploadFile(string url, string file, string paramName, string contentType)
{
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Debug(string.Format("Uploading {0} to {1}", file, url));
string boundary = "A300x";// "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream rs = wr.GetRequestStream();
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, "TEMPTEST.docx", contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
MessageBox.Show("Success!");
}
catch (Exception ex)
{
log.Error("Error uploading file", ex);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
MessageBox.Show("There was an error!" + Environment.NewLine + ex.Message);
}
finally
{
wr = null;
}
}
Can anyone see what my problem would be? I initially had my scope not set to be able to write but have corrected that so it is not the issue.
I would guess that content-disposition header is wrong. The spec says the header should look like
Content-Disposition: Attachment; filename=example.html

Categories