I am using POST to sent a byte array and a string to the server but is not sucessfull, am I doing the right thing?
memStream.Write(image, 0, signature.Length);, image is a byte array.
Code:
Uri wsHost = new Uri(WebServices.RESTEnpointAddress());
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(wsHost);
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
// Boundary
var boundary = "------------------------" + DateTime.Now.Ticks.ToString("x");
// Set the request type
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
request.KeepAlive = true;
//request.ContentLength = docByte.Length;
// Create a new memory stream
Stream memStream = new MemoryStream();
// Boundary in bytes
byte[] boundaryByte = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
// body
memStream.Write(boundaryByte, 0, boundaryByte.Length);
string ImgBody = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", "signImg", "tmpSignImgName");
ImgBody += "Content-Type: application/octet-stream\r\n\r\n";
byte[] ImgBodyByte = Encoding.ASCII.GetBytes(ImgBody);
memStream.Write(ImgBodyByte, 0, ImgBodyByte.Length);
memStream.Write(image, 0, signature.Length); // image ss a byte array
memStream.Write(boundaryByte, 0, boundaryByte.Length);
string signLocLatBody = string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n", "signloclat");
signLocLatBody += latitude;
byte[] signLocLatBodyByte = Encoding.ASCII.GetBytes(signLocLatBody);
memStream.Write(signLocLatBodyByte, 0, signLocLatBodyByte.Length);
memStream.Write(boundaryByte, 0, boundaryByte.Length);
Stream stream = request.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
stream.Write(tempBuffer, 0, tempBuffer.Length);
stream.Close();
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(MyUrl);
webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
webRequest.Method = "POST";
using (Stream requestStream = webRequest.GetRequestStream())
{
// write boundary bytes
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
// write header bytes.
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "MyName", "MyFileName", "content type");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
requestStream.Write(headerbytes, 0, headerbytes.Length);
using (MemoryStream memoryStream = new MemoryStream(imageBytes))
{
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = memoryStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
}
// write trailing boundary bytes.
byte[] trailerBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
requestStream.Write(trailerBytes, 0, trailerBytes.Length);
}
using (HttpWebResponse wr = (HttpWebResponse)webRequest.GetResponse())
{
using (Stream response = wr.GetResponseStream())
{
// handle response stream.
}
}
This reads a MemoryStream and writes the data to the requestStream, with a 4096 byte buffer. This should be wrapped in a try-catch so it can trap exceptions and handle them.
Use WebRequest for Posting data as :
WebRequest request = WebRequest.Create ("MyURL");
request.Method = "POST";
string postData = "This is a test that posts this string to a Web server.";
request.ContentType = "image/jpeg";
request.ContentLength = byteArray.Length;
//Here is the Business end of the code...
Stream dataStream = request.GetRequestStream ();
dataStream.Write (byteArray, 0, byteArray.Length);
dataStream.Close ();
//and here is the response.
WebResponse response = request.GetResponse ();
//Writing response from server
dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
Console.WriteLine (responseFromServer);
reader.Close ();
dataStream.Close ();
response.Close ();
You need use memStream as a reference to the request stream e.g.
Stream memStream = request.GetRequestStream();
Then when you write to it you are writing to the request.
Related
I try to Send Multipart Content as a Post to an WebService using c# HttpClient
My Code is the Following
public string UploadDocument(Stream stream)
{
MultipartContent multipart = new MultipartContent();
//multipart.Add(new StreamContent(stream), "importFile");
StreamContent content = new StreamContent(stream);
multipart.Add(content);
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = Client.PostAsync("URL to webservice", multipart).Result;
string result = response.Content.ReadAsStringAsync().Result;
//Wirft eine Exception wenn der StatusCode nicht 200 (OK) ist.
response.EnsureSuccessStatusCode();
return result;
}
I Need the Stream Content to be named, how can i do it.
I found a Java Way to do it, but in C# I don't find a Parameter "Name"
Here the Java Example (see "importFile")
httpRequest = new HttpPostwebviewer/?action=import");
// set headers
httpRequest.setHeader(HEADER_NAME_ACCEPT, "application/json");
// prepare upload entity
MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
meBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
meBuilder.setCharset(Consts.UTF_8);
meBuilder.addPart("importFile", contentBody);
// build upload entity
HttpEntity uploadEntity = meBuilder.build();
// set properties to http request
((HttpPost) httpRequest).setEntity(uploadEntity);
You can use System.Net.HttpWebRequest to do the same, Below is the code that I am using:
public static void UploadFile(string url, string 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");
url = handlerLocation + url;
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, file, 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);
}
catch (Exception ex)
{
//WriteTrace(ex.Message);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
(i'm french, sorry for my english)
I don't find / understand how send a simple PDF file by post request at a webService (REST protocol).
I tried some examples but it's doesn't word. And when i use a , it's work, but i want do this in the code behind only !
My question is the title : How send this PDF file?
The url : https://test.website.fr/Website/api/transactions/" + sVal + "/contrat
PDF file : questions.pdf
Thanks.
Iris Touchard
I found the solution :
//Identificate separator
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
//Encoding
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
//Creation and specification of the request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://test.website.fr/Website/api/transactions/" + sVal + "/contrat"); //sVal is id for the webService
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
string sAuthorization = "login:password";//AUTHENTIFICATION BEGIN
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(sAuthorization);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
wr.Headers.Add("Authorization: Basic " + returnValue); //AUTHENTIFICATION END
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; //For the POST's format
//Writting of the file
rs.Write(boundarybytes, 0, boundarybytes.Length);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(Server.MapPath("questions.pdf"));
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", "questions.pdf", contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(Server.MapPath("questions.pdf"), 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();
rs = null;
WebResponse wresp = null;
try
{
//Get the response
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
string responseData = reader2.ReadToEnd();
}
catch (Exception ex)
{
string s = ex.Message;
}
finally
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
wr = null;
}
This should be what you are looking for:
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
Here's a quick code example:
byte[] pdfFile = File.ReadAllBytes("pdf file path here");
WebRequest request = WebRequest.Create("https://test.site.fr/Testfile");
request.Method = "POST";
request.ContentLength = pdfFile.Length;
request.ContentType = "application/pdf";
Stream stream = request.GetRequestStream();
stream.Write(pdfFile, 0, pdfFile.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
Console.WriteLine(reader.ReadToEnd());
reader.Close();
Here is my code:
private void UploadFilesToRemoteUrl(string url, string[] files, string logpath, NameValueCollection nvc)
{
long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.KeepAlive = true;
httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
foreach(string key in nvc.Keys)
{
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
}
memStream.Write(boundarybytes,0,boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
for(int i=0;i<files.Length;i++)
{
string header = string.Format(headerTemplate,"file"+i,files[i]);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes,0,headerbytes.Length);
FileStream fileStream = new FileStream(files[i], FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
{
memStream.Write(buffer, 0, bytesRead);
}
memStream.Write(boundarybytes,0,boundarybytes.Length);
fileStream.Close();
}
httpWebRequest2.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest2.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer,0,tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer,0,tempBuffer.Length );
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
MessageBox.Show(reader2.ReadToEnd());
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
}
And here is how I call it:
string[] filenames = new string[] { #"C:\Users\John\Desktop\ex.txt" };
NameValueCollection nvc = new NameValueCollection();
nvc.Add("cmd", "new");
nvc.Add("sTitle", "bugX");
nvc.Add("token", "someToken");
UploadFilesToRemoteUrl("https://myUrl.fogbugz.com/api.asp", filenames, "", nvc);
And everything is working fine, except the file isn't uploaded.
I also tried this code:
http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data
and the same thing happens. How to resolve this?
Here is the response from the server:
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<response>
<case ixBug=\"123486\" operations=\"edit,assign,resolve,email,remind\"></case>
</response>
you're just sending a stream to the server, it's impossible to know what happens at the server for us if you don't provide any code for us from the server side. I guess you've forgotten to receive and create the file on the server side.
if this is not the problem I would suggest you get the invaluable tool fiddler and start catching your httprequests and see what they contain.
guys, first of all thanks for your contributions, I've found great responses here. Yet I've ran into a problem I can't figure out and if someone could provide any help, it would be greatly appreciated.
I'm developing this application in C# that could upload an image from computer to user photoblog. For this I'm usig pixelpost platform for photoblogs that is written mainly in PHP.
I've searched here and on other web pages, but the exmples provided there didn't work for me.
Here is what I used in my example: (Upload files with HTTPWebrequest (multipart/form-data))
and
(http://bytes.com/topic/c-sharp/answers/268661-how-upload-file-via-c-code)
Once it is ready I will make it available for free on the internet and maybe also create a windows mobile version of it, since I'm a fan of pixelpost.
here is the code I've used:
string formUrl = "http://localhost/pixelpost/admin/index.php?x=login";
string formParams = string.Format("user={0}&password={1}", "user-String", "password-String");
string cookieHeader;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
req.AllowAutoRedirect = false;
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
cookieHeader = resp.Headers["Set-Cookie"];
string pageSource;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
Console.WriteLine();
}
string getUrl = "http://localhost/pixelpost/admin/index.php";
HttpWebRequest getRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
// end first part: login to admin panel
long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/pixelpost/admin/index.php?x=save");
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.AllowAutoRedirect = false;
httpWebRequest2.KeepAlive = false;
httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
httpWebRequest2.Headers.Add("Cookie", cookieHeader);
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
string formitem = string.Format(formdataTemplate, "headline", "image-name");
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
memStream.Write(boundarybytes, 0, boundarybytes.Length);
string 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, "userfile", "path-to-the-local-file");
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream("path-to-the-local-file", FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
fileStream.Close();
httpWebRequest2.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest2.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
Console.WriteLine(reader2.ReadToEnd());
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
and also here is the PHP:
(http://dl.dropbox.com/u/3149888/index.php)
and
(http://dl.dropbox.com/u/3149888/new_image.php)
the mandatory fields are headline and userfile so I can't figure out where the mistake is, as the format sent in right. I'm guessing there is something wrong with the octet-stream sent to the form.
Maybe it's a stupid mistake I wasn't able to trace, in any case, if you could help me that would mean a lot.
thanks,
So Martin helped me out here and I was able to make the important changes to the code above in order for it to work properly.
The Content-Type had to be changed to image/jpeg. Also I used C# Image type to send image stream.
Also pay attention to the Stream format, as it does not have to contain extra spaces or new lines.
here is the changed part:
string formUrl = "http://localhost/pixelpost/admin/index.php?x=login";
string formParams = string.Format("user={0}&password={1}", "username", "password");
string cookieHeader;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(formUrl);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
req.AllowAutoRedirect = false;
byte[] bytes = Encoding.ASCII.GetBytes(formParams);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
cookieHeader = resp.Headers["Set-Cookie"];
string pageSource;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
string getUrl = "http://localhost/pixelpost/admin/index.php";
HttpWebRequest getRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
getRequest.Headers.Add("Cookie", cookieHeader);
HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
pageSource = sr.ReadToEnd();
}
long length = 0;
string boundary = "----------------------------" +
DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create("http://localhost/pixelpost/admin/index.php?x=save");
httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest2.Method = "POST";
httpWebRequest2.AllowAutoRedirect = false;
httpWebRequest2.KeepAlive = false;
httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
httpWebRequest2.Headers.Add("Cookie", cookieHeader);
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary);
string headerTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: image/jpeg\r\n\r\n";
string header = string.Format(headerTemplate, "userfile", "Sunset.jpg");
byte[] headerbytes = System.Text.Encoding.ASCII.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
Image img = null;
img = Image.FromFile("C:/Documents and Settings/Dorin Cucicov/My Documents/My Pictures/Sunset.jpg", true);
img.Save(memStream, System.Drawing.Imaging.ImageFormat.Jpeg);
memStream.Write(boundarybytes, 0, boundarybytes.Length);
string formdataTemplate = "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
string formitem = string.Format(formdataTemplate, "headline", "Sunset");
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
memStream.Write(formitembytes, 0, formitembytes.Length);
memStream.Write(boundarybytes, 0, boundarybytes.Length);
httpWebRequest2.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest2.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
WebResponse webResponse2 = httpWebRequest2.GetResponse();
Stream stream2 = webResponse2.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
Console.WriteLine(reader2.ReadToEnd());
webResponse2.Close();
httpWebRequest2 = null;
webResponse2 = null;
Thank you all again for answering or just reading.
using C#, I'm trying to integrate my web store w/ an email marketing client. I want to upload a comma delimited file of subscribers once a night. They say to get this to work, it has to be a form posts: multipart/form-data, but I'm not using a form. I'm able to connect to their servers but I keep getting back a Data can't be blank. Can anyone help me to get this working?
public static string Create()
{
string authInfo = "username" + ":" + "password";
string root = AppDomain.CurrentDomain.BaseDirectory;
string file = root + "Folder\\work.txt";
FileInfo fi = new FileInfo(file);
int fileLength = (int)fi.Length;
FileStream rdr = new FileStream(file, FileMode.Open);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Accept = "application/xml";
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
httpWebRequest.Headers["Authorization"] = "Basic " + authInfo;
byte[] requestBytes = new byte[fileLength];
int bytesRead = 0;
httpWebRequest.ContentLength = requestBytes.Length;
using (Stream requestStream = httpWebRequest.GetRequestStream())
{
while ((bytesRead = rdr.Read(requestBytes, 0, requestBytes.Length)) != 0)
{
requestStream.Write(requestBytes, 0, bytesRead);
requestStream.Close();
}
}
//READ RESPONSE FROM STREAM
string responseData;
using (StreamReader responseStream = new StreamReader(httpWebRequest.GetResponse().GetResponseStream()))
{
responseData = responseStream.ReadToEnd();
responseStream.Close();
}
return responseData;
}
I had got the same problem and this following code answered perfectly at this problem :
//Identificate separator
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
//Encoding
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
//Creation and specification of the request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url); //sVal is id for the webService
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
string sAuthorization = "login:password";//AUTHENTIFICATION BEGIN
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(sAuthorization);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
wr.Headers.Add("Authorization: Basic " + returnValue); //AUTHENTIFICATION END
Stream rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; //For the POST's format
//Writting of the file
rs.Write(boundarybytes, 0, boundarybytes.Length);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(Server.MapPath("questions.pdf"));
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", "questions.pdf", contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(Server.MapPath("questions.pdf"), 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();
rs = null;
WebResponse wresp = null;
try
{
//Get the response
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
string responseData = reader2.ReadToEnd();
}
catch (Exception ex)
{
string s = ex.Message;
}
finally
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
wr = null;
}