MVC | Upload file on FTP
Upload file on Server using FTP detail in mvc C#.
Code:
public static class FileUpload { public static string FTPUpload(HttpPostedFileBase file) { // //FTP Server URL. string ftp = ConfigurationSettings.AppSettings["ftpName"].ToString(); // //FTP Folder name. Leave blank if you want to upload to root folder. string ftpFolder = ConfigurationSettings.AppSettings["ftpFolder"].ToString(); byte[] fileBytes = null; // //Read the FileName and convert it to Byte array. string fileName = Path.GetFileName(file.FileName); using (StreamReader fileStream = new StreamReader(file.InputStream)) { fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd()); fileStream.Close(); } try { //Create FTP Request. string path = ftp + ftpFolder + fileName; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(path); request.Method = WebRequestMethods.Ftp.UploadFile; //Enter FTP Server credentials. request.Credentials = new NetworkCredential(ConfigurationSettings.AppSettings["ftpUsername"].ToString(), ConfigurationSettings.AppSettings["ftpPassword"].ToString()); request.ContentLength = fileBytes.Length; request.UsePassive = true; request.UseBinary = true; 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 (ex.Response as FtpWebResponse).StatusDescription; } catch (Exception e) { return e.Message; } return "success"; } }
Configuration settings:
<appSettings> <add key="ftpName" value="ftp://testftp/"></add> <add key="ftpUsername" value="username"></add> <add key="ftpPassword" value="password"></add> <add key="ftpFolder" value="folderpath"></add> </appSettings>
No comments:
Post a Comment