Uploading file using Httpwebrequest - c#

I want to upload file to a server. I wrote this function to upload the file to localhost server (I am using wamp server):
private void button1_Click_1(object sender, EventArgs e)
{
FileStream fstream = new FileStream(#"C:\Users\Albert\Documents\10050409_3276.doc", FileMode.OpenOrCreate);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/upload_file");
request.Method = "PUT";
request.ContentLength = fstream.Length;
request.AllowWriteStreamBuffering = true;
Stream request_stream = request.GetRequestStream();
byte[] indata = new byte[1024];
int bytes_read = fstream.Read(indata, 0, indata.Length);
while (bytes_read > 0)
{
request_stream.Write(indata, 0, indata.Length);
bytes_read = fstream.Read(indata, 0, indata.Length);
}
fstream.Close();
request_stream.Close();
request.GetResponse();
MessageBox.Show("ok");
}
So when i click on the button the exception apper said that:
Additional information: The remote server returned an error: (405) Method Not Allowed.
I tried to use "POST" instead of "PUT" so the program works and the message box appears to say 'ok', but when i open the localhost->upload_file(folder) Ididn't find any files.
I tested my program with wamp server => the problem occured.
I tested my program with real server and put in the network credentials and tried to upload to folder that has (777) permission => the problem occured.
So where is the problem exactly?
Thanks :)

try with webClient
WebClient client = new WebClient();
byte[] bret = client.UploadFile(path, "POST", FilePath);
//path==URL
//FilePath==Your uploading file path
or
WebClient webClient = new WebClient();
string webAddress = null;
try
{
webAddress = #"http://localhost/upload_file/";
webClient.Credentials = CredentialCache.DefaultCredentials;
WebRequest serverRequest = WebRequest.Create(webAddress);
serverRequest.Credentials = CredentialCache.DefaultCredentials;
WebResponse serverResponse;
serverResponse = serverRequest.GetResponse();
serverResponse.Close();
webClient.UploadFile(path, "POST", FilePath);
webClient.Dispose();
webClient = null;
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
(code in or part i didn't tried )

Related

Http post request to send form data in image format

Hi I have below code to send the data, but in return I get server error with error code 500, the file is
not getting sent through the request
Can anyone tell me what I am doing wrong
FileStream rdr = new FileStream("C:/Users/AR485UY/Desktop/Test1.pdf", FileMode.Open)
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("url" );
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
req.Method = "POST";
req.ContentLength = rdr.Length;
req.ContentType = "multipart/form-data; boundary=" +boundary;
req.AllowWriteStreamBuffering = true;
Stream reqStream = req.GetRequestStream();
byte[] inData = new byte[rdr.Length];
int len = Convert.ToInt32(rdr.Length);
int bytesRead = rdr.Read(inData, 0, len);
reqStream.Write(inData, 0, len);
rdr.Close();
req.GetResponse();
reqStream.Close();
HTTP 500 Internal Server Error server error response code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
if it never work :
Most likely have to validate your server side api,script,logs,events,diagnostics trace,file size limits.
Also try another approach in c#:
try
{
using(WebClient client = new WebClient())
{
string myFile = #"C:/Users/AR485UY/Desktop/Test1.pdf";
client.Credentials = CredentialCache.DefaultCredentials;
client.UploadFile(url, "POST", myFile);
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}

Save file in a folder on another server location with the purely written code on website

I am using mvc I am trying to save a file on another folder i.e on another server.
But earlier i was using an approach of creating two different solution and was saving the file using web request.
i was sending the request from one solution and was geeting it on another solution.
here is my code
byte[] bytes;
var pic = System.Web.HttpContext.Current.Request.Files["ImagePath"];
/*Creating the WebRequest object using the URL of SaveFile.aspx.*/
System.Net.HttpWebRequest webRequest =
(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create
("http://localhost:13492/Home/SaveImage");
webRequest.Method = "POST";
webRequest.KeepAlive = false;
/*Assigning the content type from the FileUpload control.*/
webRequest.ContentType = pic.ContentType ;
/*Creating the Header object.*/
System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();
headers.Add("FileName", pic.FileName);
/*Adding the header to the WebRequest object.*/
webRequest.Headers = headers;
/* Convert File Into byte array */
using (var stream = new MemoryStream())
{
pic.InputStream.CopyTo(stream);
bytes = stream.ToArray();
}
/*Getting the request stream by making use of the GetRequestStream method of WebRequest object.*/
using (System.IO.Stream stream = webRequest.GetRequestStream())//Filling request stream with image stream.
{
/*Writing the FileUpload content to the request stream.*/
stream.Write(bytes, 0, pic.ContentLength);
}
/*Creating a WebResponse object by calling the GetResponse method of WebRequest object.*/
using (System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse())
{
/*Retrieving the response stream from the WebResponse object by calling the GetResponseStream method.*/
using (System.IO.StreamReader sr = new System.IO.StreamReader(webResponse.GetResponseStream()))
{
string path = sr.ReadToEnd();
}
}
then in another solution i was getting it to save the file.
public void SaveImage()
{
try
{
/*Retrieving the file name from the headers in the request. */
string destinationFileName = Path.Combine(#"~/" + "Portfolio" + "/", Request.Headers["FileName"].ToString());
string fileName = System.Web.HttpContext.Current.Server.MapPath(destinationFileName);
//string path = System.IO.Path.Combine(Server.MapPath("."), Request.Headers["FileName"].ToString());
using (System.IO.FileStream fileStream = System.IO.File.Create(fileName))
{
/*Getting stream from the Request object.*/
using (System.IO.Stream stream = Request.InputStream)
{
int byteStreamLength = (int)stream.Length;
byte[] byteStream = new byte[byteStreamLength];
/*Reading the stream to a byte array.*/
stream.Read(byteStream, 0, byteStreamLength);
/*Writing the byte array to the harddisk.*/
fileStream.Write(byteStream, 0, byteStreamLength);
}
}
Response.Clear();
/*Writing the status to the response.*/
Response.Write(fileName);
}
catch (Exception ex)
{
/*Writing the error message to the response stream.*/
Response.Clear();
Response.Write("Error: " + ex.Message);
}
}
So what should i change in code so that i could save the file on another location on another server without writing the code on two different place.
I've got a solution for this problem and its working fine.
public static void UploadFtpFile(string folderName, string fileName)
{
FtpWebRequest request;
try
{
//string folderName;
//string fileName;
string absoluteFileName = Path.GetFileName(fileName);
request = WebRequest.Create(new Uri(string.Format(#"ftp://{0}/{1}/{2}", "ftp.site4now.net", folderName, absoluteFileName))) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = true;
request.Credentials = new NetworkCredential("Username", "Password");
request.ConnectionGroupName = "group";
using (FileStream fs = System.IO.File.OpenRead(fileName))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Flush();
requestStream.Close();
}
}
catch (Exception ex)
{
}
}
Follow Below Sample
This sample is for creating a folder on another server over FTP protocol. Please extend it as per need.
using System;
using System.Net;
class Test
{
static void Main()
{
WebRequest request = WebRequest.Create("ftp://host.com/directory");
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("user", "pass");
using (var resp = (FtpWebResponse) request.GetResponse())
{
Console.WriteLine(resp.StatusCode);
}
}
}
As per the comment by #ADyson you must enable the FTP Protocol before working using this sample

Unable to connect to server when uploading file using FTP

I am working with mvc 4.5 trying to upload an image using FTP.
My code:
public virtual void Send(HttpPostedFileBase uploadfile, string fileName)
{
Stream streamObj = uploadfile.InputStream;
byte[] buffer = new byte[uploadfile.ContentLength];
streamObj.Read(buffer, 0, buffer.Length);
streamObj.Close();
string ftpurl = String.Format("{0}/{1}/{2}", _remoteHost, _foldersHost, fileName);
var request = FtpWebRequest.Create(ftpurl) as FtpWebRequest;
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UsePassive = false;
request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
request.ContentLength = buffer.Length;
var requestStream = request.GetRequestStream();
requestStream.Write(buffer, 0, buffer.Length);
requestStream.Close();
var response = (FtpWebResponse) request.GetResponse();
if (response != null)
response.Close();
}
The code is working on localhost, I am able to conect to the FTP server and upload the file, but the problem comes once the project is published. I am using SmarterASP to host the site. When I try to upload the image on production, the uploading method gives me an exception, the message says "Unable to connect to the remote server".
Any clue or workaround?
Exception details:
System.Net.FtpWebRequest.GetRequestStream() at AgileResto.Controllers.RestaurantsController.Send(HttpPosted‌​FileBase uploadfile, String fileName) at AgileResto.Controllers.RestaurantsController.UploadFile(Int3‌​2 RestaurantList, HttpPostedFileBase file, HttpPostedFileBase file2)
you need to grant write permission in the server to the folder you are saving the file to

HttpWebRequest Issue to remote server

I'm trying to upload files to a remote server (windows server 2008 R2) from my asp.net 1.1 (C#) Windows application (I know.. It's really old, sadly, that's what we have). When I try to upload, it's giving me an error: "The remote server returned an error: (404) Not Found.".
Here's the code I'm using:
Any ideas?
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uploadUrl);
req.Credentials = new NetworkCredential(uName,pwd);
req.Method = "PUT";
req.AllowWriteStreamBuffering = true;
// Retrieve request stream
Stream reqStream = req.GetRequestStream();
// Open the local file
FileStream rdr = new FileStream(txt_filename.Text, FileMode.Open);
// Allocate byte buffer to hold file contents
byte[] inData = new byte[4096];
// loop through the local file reading each data block
// and writing to the request stream buffer
int bytesRead = rdr.Read(inData, 0, inData.Length);
while (bytesRead > 0)
{
reqStream.Write(inData, 0, bytesRead);
bytesRead = rdr.Read(inData, 0, inData.Length);
}
rdr.Close();
reqStream.Close();
req.GetResponse();
The uploadUrl is like this: http://10.x.x.x./FolderName/Filename
Please use "POST" method instead of "PUT" and I guess it will work.
Edit:
Check the code below, it will help you.
public void UploadFile()
{
string fileUrl = #"enter file url here";
string parameters = #"image=" + Convert.ToBase64String(File.ReadAllBytes(fileUrl));
WebRequest req = WebRequest.Create(new Uri("location url here"));
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
try
{
req.ContentLength = bytes.Length;
Stream s = req.GetRequestStream();
s.Write(bytes, 0, bytes.Length);
s.Close();
}
catch (WebException ex)
{
throw ex; //Request exception.
}
try
{
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(req.GetResponseStream());
}
catch (WebException ex)
{
throw ex; //Response exception.
}
}
Enter fileUrl variable correctly and take care of uri while creating WebRequest instance, write the url of the locating folder.

Uploading files to FTP are corrupted once in destination

I'm creating a simple drag-file-and-upload-automatically-to-ftp windows application
and I'm using the MSDN code to upload the file to the FTP.
The code is pretty straight forward:
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(String.Format("{0}{1}", FTP_PATH, filenameToUpload));
request.Method = WebRequestMethods.Ftp.UploadFile;
// Options
request.UseBinary = true;
request.UsePassive = false;
// FTP Credentials
request.Credentials = new NetworkCredential(FTP_USR, FTP_PWD);
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(fileToUpload.FullName);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
writeOutput("Upload File Complete!");
writeOutput("Status: " + response.StatusDescription);
response.Close();
and it does get uploaded to the FTP
Problem is when I see the file on a browser, or simply download and try to see it on desktop I get:
I already used request.UseBinary = false; and request.UsePassive = false; but it does not seam to do any kind of good whatsoever.
What I have found out was that, the original file has 122Kb lenght and in the FTP (and after downloading), it has 219Kb...
What am I doing wrong?
By the way, the uploadFileToFTP() method is running inside a BackgroundWorker, but I don't really thing that makes any difference...
You shouldn't use a StreamReader but only a Stream to read binary files.
Streamreader is designed to read text files only.
Try with this :
private static void up(string sourceFile, string targetFile)
{
try
{
string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];
string ftpUserID = ConfigurationManager.AppSettings["ftpUser"];
string ftpPassword = ConfigurationManager.AppSettings["ftpPass"];
////string ftpURI = "";
string filename = "ftp://" + ftpServerIP + "//" + targetFile;
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
byte[] b = File.ReadAllBytes(sourceFile);
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
if (ftpResp != null)
{
MessageBox.Show(ftpResp.StatusDescription);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The problems are caused by your code decoding the binary data to character data and back to binary data. Don't do this.
Use the UploadFile Method of the WebClient Class:
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(FTP_USR, FTP_PWD);
client.UploadFile(FTP_PATH + filenameToUpload, filenameToUpload);
}

Categories

Resources