Hi nauna,
HTML
<div>
<asp:FileUpload ID="FuClass" runat="server" />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Upload" OnClick="btnSubmit_Click" />
</div>
Code
CS.aspx.cs
using System;
public partial class CS : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
Class1 cl = new Class1();
string file = cl.Upload(FuClass);
}
}
Class1.cs
using System;
using System.IO;
using System.Net;
using System.Web.UI.WebControls;
public class Class1
{
public string Upload(FileUpload FileUpload1)
{
string path = "";
string uploadFileName = "";
if (FileUpload1.HasFile)
{
string ext = Path.GetExtension(FileUpload1.FileName).ToLower();
if (ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".png")
{
uploadFileName = Guid.NewGuid().ToString() + ext;
}
//FTP Server URL.
string ftp = "ftp://onlinehcs.com/";
//FTP Folder name. Leave blank if you want to upload to root folder.
string ftpFolder = "ftpfolder paramater";
byte[] fileBytes = null;
//Read the FileName and convert it to Byte array.
string fileName = Path.GetFileName(uploadFileName);
FileUpload1.PostedFile.InputStream.Seek(0, SeekOrigin.Begin);
using (var binaryReader = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
fileBytes = binaryReader.ReadBytes(FileUpload1.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("username ", "password");
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();
path = "domainname/Dynamicimage/" + uploadFileName;
response.Close();
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
}
return path;
}
}