0
Hello, my problem is this, I have a simple web application running on apache on localhost.
Which has the following code:
<?php
if (isset($_FILES['arquivo']))
{
move_uploaded_file($_FILES['arquivo']['tmp_name'], "uploadedfile.pdf");
}
?>
<HTML>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="arquivo" id="arquivo"/>
<input type="submit" value="click here to send"/>
</form>
</HTML>
I would like to know how to upload my desired file in c# using httpwebrequest.
I tried the following:
public string Upload(string filePath)
{
string formdataTemplate = "Content-Disposition: form-data;name=\"arquivo\" ;filename=\"{0}\";\r\nContent-Type: application/pdf\r\n\r\n";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/xxxx/fileuploader.php");
request.ServicePoint.Expect100Continue = false;
request.Referer = "http://localhost/policlinica/fileuploader.php";
request.KeepAlive = false;
request.Method = "POST";
request.CookieContainer = cookieContainer;
request.ContentType = "multipart/form-data; boundary=" + boundary;
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, Path.GetFileName(filePath));
byte[] formbytes = Encoding.UTF8.GetBytes(formitem);
requestStream.Write(formbytes, 0, formbytes.Length);
byte[] buffer = new byte[1024 * 4];
int bytesLeft = 0;
while ((bytesLeft = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
requestStream.Write(buffer, 0, bytesLeft);
}
}
}
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
}
catch (WebException ex)
{
return ex.ToString();
}
}
But without success.
Thank you.
Show us what you’ve done with C# using Webrequest.
– CypherPotato