Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

upload to ftp asp.net

Is it possible to upload a file directly into an ftp account folder with ASP.NET ?

E.g. I click on browse, select a file to upload and when I click "upload" button, It should save it directly to the folder on another web server located at somewhere else other then the server that is being used to upload.

like image 532
Subliminal Hash Avatar asked May 08 '09 07:05

Subliminal Hash


2 Answers

As I understand your question, you want to upload the file to another remote server (so it's not another server sitting on the same network as your web server)? In that case you can do a couple of different things. The easiest way is perhaps to start by making a regular file upload you your server, and then have your server send the file via FTP to the other remote server:

string fileName = Path.Combine("<path on your server", FileUpload1.FileName);
FileUpload1.SaveAs(fileName);
using(System.Net.WebClient webClient = new System.Net.WebClient())
{
    webClient.UploadFile(
        New Uri("ftp://remoteserver/remotepath/" + FileUpload1.FileName), 
        localFile);
}

...or it might work doing it in one step:

using(System.Net.WebClient webClient = new System.Net.WebClient())
{
    webClient.UploadData(
        New Uri("ftp://remoteserver/remotepath/" + FileUpload1.FileName), 
        FileUpload1.FileBytes);
}

(I din't try this code out, so there could be some errors in it...)

Update: I noticed that I was wrong in assuming that the UploadXXX methods of WebClient were static...

like image 92
Fredrik Mörk Avatar answered Oct 03 '22 11:10

Fredrik Mörk


You can use the WebClient class to store the uploaded file to FTP (without saving it as a file on the server). Something like this:

string name = Path.GetFileName(UploadControl.FileName);
byte[] data = UploadControl.FileBytes;

using (WebClient client = new WebClient()) {
   client.UploadData("ftp://my.ftp.server.com/myfolder/" + name, data);
}
like image 35
Guffa Avatar answered Oct 03 '22 12:10

Guffa