How to upload images and video to a web server? - c#

I have the following code. The upload was successfully but the images and videos are broken. I think the problem is because the encoding set to UTF8. How do I upload images and videos to the web server in C#?
private static void Upload(string ftpFilePath, string file)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFilePath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(Properties.Settings.Default.FtpUser, Properties.Settings.Default.FtpPass);
using (Stream fileStream = File.OpenRead(file))
using (Stream ftpStream = request.GetRequestStream())
{
fileStream.CopyTo(ftpStream);
}
FtpWebResponse response = null;
try
{
response = (FtpWebResponse)request.GetResponse();
// Output message on screen
Log.Write($"{request.Method} {ftpFilePath}", Log.Status.UPLOADED);
}
catch (Exception ex)
{
// Output message on screen
Log.Write($"FTP UPLOAD: {response.StatusCode} - {ex.Message}", Log.Status.ERROR);
}
}

Related

window photo viewer cant open this picture because the file appears to be damaged, corrupted or is too large

i am using c# to upload a file from one server to another server . file is uploaded successfully but when i am trying to open the file it says "it cant be open because it may be damaged, corrupted."
Here is my code
/*Creating the WebRequest object using the URL of SaveFile.aspx.*/
System.Net.HttpWebRequest webRequest =
(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create
("http://localhost:19889/SaveFiles/SaveFile.aspx");
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;
var fileByte = new byte[pic.ContentLength];
/*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(fileByte, 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()))
{
// lblMessage.Text = sr.ReadToEnd();
}
}
and this is code of savefile.aspx
protected void Page_Load(object sender, EventArgs e)
{
try
{
/*Retrieving the file name from the headers in the request. */
string fileName = 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("File successfully saved");
}
catch (Exception ex)
{
/*Writing the error message to the response stream.*/
Response.Clear();
Response.Write("Error: " + ex.Message);
}
}

C#: ftp upload is successful but dowloaded file is damaged

I'm using the code bellow to upload a zip file to to my ftp server:
string zipPath = #"d:\files\start.zip";
string ftpPath = ("ftp://######/start.zip");
WebRequest request = WebRequest.Create(ftpPath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("######", "######");
StreamReader sourceStream = new StreamReader(zipPath);
byte[] fileContents = Encoding.Unicode.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
try
{
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse makeFileUploadResponse = (FtpWebResponse)request.GetResponse();
}
catch
{
MessageBox.Show("ftp failed!");
}
My zip archive is definitely valid (I can open it and extract it) but when I download the uploaded zip file, I got the error that archive is damaged.
Update 1: my source code is from MSDN article:How to: Upload Files with FTP
you should cast request to FtpWebRequest (as in that MSDN example)
and then specify request as binary (you're uploading binary file, not text).
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("aa");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.UseBinary = true;
I can't say what the problem is but I can provide an alternate solution. You can use WebClient instead of WebRequest
string zipPath = #"d:\files\start.zip";
string ftpPath = ("ftp://######/start.zip");
WebClient ftpClient = new WebClient();
ftpClient.Credentials = new NetworkCredential("####", "######");
try{
ftpClient.UploadFile(ftpPath, WebRequestMethods.Ftp.AppendFile, zipPath);
}
catch(WebException ex){
MessageBox.Show("ftp failed");
}

Incomplete/Corrupted downloaded files

I have made this little tool wich goes through a list of image links and download them to the hard drive, however, some of the pictures are incomplete (Check this picture) and they don't even raise an exception. The code below shows the download method I'm using in my tool.
private void Download(string url)
{
try
{
HttpWebRequest Request = WebRequest.Create(url) as HttpWebRequest;
Request.Method = WebRequestMethods.Http.Get;
Request.Timeout = 60 * 1000;
FileInfo ImageFile = new FileInfo(Path.Combine(BaseDirectory, Path.GetFileName(url)));
if (!ImageFile.Exists)
{
using (HttpWebResponse Response = Request.GetResponse() as HttpWebResponse)
{
if (Response.StatusCode.Equals(HttpStatusCode.OK))
{
using (FileStream FStream = new FileStream(ImageFile.FullName, FileMode.Create, FileAccess.Write, FileShare.None, 4096))
Response.GetResponseStream().CopyTo(FStream, 4096);
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Error Downloading: {0}\r\nMessage: {1}", url, e.Message);
}
}
I can't figure out whether the problem is on the server side or there is something wrong with my code, so what do you think?
Have you tried calling Flush() after you've read the data? It looks like the last part of the stream isn't being written out.

The remote server returned an error: (421) Service not available, closing control connection

I am running this code for alot of files to transfer locally to another server via ftp. The problem is I am periodically getting the error The remote server returned an error: (421) Service not available, closing control connection. Is there a problem with the code, a better way to transfer the files that is quicker more efficient. All the files need to be transfered so I was thinking a while loop and catching the error until all files in the folder have transfered. It is a periodic error I am getting:
foreach (FileInfo file in files)
{
try
{
// Get the object used to communicate with the server.
FtpWebRequest request =
(FtpWebRequest)
WebRequest.Create(String.Format("{0}{1}/{2}", Host, destinationPath,
file.Name));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = false;
/* 20 mins timeout */
request.Timeout = 1200000;
request.ReadWriteTimeout = 1200000;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential(Username, Password);
// Copy the contents of the file to the request stream.
byte[] fileContents = File.ReadAllBytes(file.FullName);
request.ContentLength = fileContents.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
//using (FtpWebResponse response = (FtpWebResponse) request.GetResponse())
//{
//}
if (deleteSourcePath)
{
File.Delete(file.FullName);
}
}
catch (Exception ex)
{
// Log.Warn("Error Moving Images", ex.Message);
}
}
Call Close on the the FtpWebResponse object. That will release the associated port.
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
// ...
finally
{
if (response != null)
{
response.Close();
}
}

Upload PDF files through FTP in C Sharp

I have the following code to upload a pdf file through ftp :
try
{
if (!File.Exists(localPath))
throw new FileNotFoundException(localPath);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpPath));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Proxy = null;
request.UseBinary = true;
request.Credentials = new NetworkCredential(username, password);
byte[] data = File.ReadAllBytes(localPath);
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
if (response == null || (response.StatusCode != FtpStatusCode.CommandOK))
throw new Exception("Upload failed.");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
throw e;
}
My problem that it uploads only text without images . How could i upload a file without reading it? I mean i just want to select and rename the file and upload it.
Use the WebClient class and use then the UploadFile Method.
From msdn
String uriString = Console.ReadLine();
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
myWebClient.Credentials=new NetworkCredential(username, password);
Console.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URI");
string fileName = Console.ReadLine();
Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);
// Upload the file to the URI.
// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
byte[] responseArray = myWebClient.UploadFile(uriString,fileName);

Categories