FTP upload in ASP.NET MVC 5 POST action

Programming ASP.NET C#

Simple upload Form in Index View:

<form method="post" enctype="multipart/form-data">
<input type="file" id="postedFile" name="postedFile" />
<input type="submit" value="send" />
</form>

In our Controller we now need a POST action like this: 

[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile)
{
// FTP Server URL
string ftp = "ftp://ftp.YourServer.com/";

// FTP Folder name. Leave blank if you want to upload to root folder
// (really blank, not "/" !)
string ftpFolder = "test/";
byte[] fileBytes = null;
string ftpUserName = "YourUserName";
string ftpPassword = "YourPassword";

// read the File and convert it to Byte array.
string fileName = Path.GetFileName(postedFile.FileName);
using (BinaryReader br = new BinaryReader(postedFile.InputStream))
{
fileBytes = br.ReadBytes(postedFile.ContentLength);
}

try
{
// create FTP Request
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;

// enter FTP Server credentials
request.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
request.ContentLength = fileBytes.Length;
request.UsePassive = true;
request.UseBinary = true; // or FALSE for ASCII files
request.ServicePoint.ConnectionLimit = fileBytes.Length;
request.EnableSsl = false;

using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileBytes, 0, fileBytes.Length);
requestStream.Close();
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
return View();
}

For uploading large files you can add this line to your web.config under system.web section (the default is 4 MB size limit).

<httpRuntime maxRequestLength="value in KB (f.e: 51200 = 50MB)" relaxedUrlToFileSystemMapping="true" />