Site icon GetCodify

How to upload file to ftp using C#(C-Sharp) – aspx,ashx and ajax

In this article, we are going to explain how to upload the file to FTP using C# Generic handler(.ashx), HTML and Ajax.

Please follow the steps below

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
jquery google CDN link
 <div>
        <input type="file" id="fileupload"/>

        <button type="button" id="submithere">upload</button>
    </div>
HTML for File Upload
<script>
        $(document).ready(function () {
            $("#submithere").click(function () {

            var formData = new FormData();// it creats form object
            formData.append('file', $('#fileupload')[0].files[0]); //it reads file from from HTML form
                        
                $.ajax({
                    type: 'post',//method i which we need to upload the file
                    url: 'fileupload.ashx',//the is the .ashx fileuload handler
                    data: formData,//file data
                    success: function (status) {
                        alert(status);//status here is returned with the file url where it is stored with path from this save the file name to DB.
                    },
                    processData: false,
                    contentType: false,
                    error: function () {
                        overlayProgress.remove();
                        console.error("Whoops something went wrong!");
                    }
                });
            });
        });
    </script>
public void ProcessRequest(HttpContext context)
        {
            try
            {
                string halfpath = "Uploads/";//path for ftpupload
                string str_image = "";
                long ticks = DateTime.Now.Ticks; //using date creating unique file.
                foreach (string s in context.Request.Files)//here we can upload single/multiple files at a time. 
                {
                    HttpPostedFile file = context.Request.Files[s];
                    string fileName = file.FileName;
                    string fileExtension = file.ContentType;//get file extension

                    if (!string.IsNullOrEmpty(fileName))
                    {
                        fileExtension = Path.GetExtension(fileName);
                        str_image = "file" + ticks.ToString() + fileExtension;
                        string localpath = HttpContext.Current.Server.MapPath("~/Uploads/") + str_image;// gets full path where the file to be uploaded.
                        file.SaveAs(localpath);// this saves the file in local application directory
                        halfpath += str_image;//here it create the full file path where file should be uploaded in FTP.
                        string res = UploadFile(localpath, halfpath);// this calls the FTP UploadFile function to upload the file.
                    }
                }
                context.Response.Write(halfpath);
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
local file upload

You might think why this file is uploading to the application(solution) local directory and then using that path it is being uploaded to FTP?, Because using Ajax – javascript, browser cannot read the physical/original path of the initial file upload PC  path because of security reason browser do not allow javascript to read, so when we select the file from PC browser create fake-path of file and upload it to local application directory, from there it creates application local path and sends to FTP for uploading File.

public static string UploadFile(string path, string upload_path)
        {
           
            string ip = "192.168.1.1";// please enter your ip/ftp url here
            string username = "username";//Enter your FTP user name
            string password = "password";//Enter your FTP password name

            string fullpath = "ftp://" + ip + "/" + upload_path; //with ip/url create a ftp path where you will upload

            FileInfo fileInf = new FileInfo(path);

            FtpWebRequest reqFTP;
            // Create FtpWebRequest object from the Uri provided
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(fullpath);
            // Provide the WebPermission Credentials
            reqFTP.Credentials = new NetworkCredential(username, password);
            reqFTP.Proxy = null; //Set Proxy to be null
            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            reqFTP.KeepAlive = false;
            // Specify the command to be executed.
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
            // Specify the data transfer type.
            reqFTP.UseBinary = true;
            // Notify the server about the size of the uploaded file
            reqFTP.ContentLength = fileInf.Length;
            //SSL
            reqFTP.EnableSsl = false;
            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            // Stream to which the file to be upload is written
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
                FileStream fs = fileInf.OpenRead();
                try
                {
                    do
                    {
                        contentLen = fs.Read(buff, 0, buffLength);
                        strm.Write(buff, 0, contentLen);
                    } while (contentLen != 0);
                    fs.Close();
                    strm.Close();
                }
                catch (WebException ex)
                {
                    String status = ((FtpWebResponse)ex.Response).StatusDescription;
                    return ex.ToString();
                }
            }
            catch (WebException ex)
            {
                String status = ((FtpWebResponse)ex.Response).StatusDescription;
                return ex.ToString();
            }
            //here it will delete the file from local application temp location after uploading to ftp server.
            if ((System.IO.File.Exists(path)))
            {
                System.IO.File.Delete(path);
            }
            return "1";
        }

FTP c# File Upload

For full project click on below button to download full demo solution.

I know this solution may not be the best, but it works for me, so if anyone knows the even easier solution please leave a link in the comment section below.

 

Exit mobile version