IT/C#

C# FTP 파일 업로드,다운로드

하루콩콩 2020. 8. 24. 12:03
반응형

C#에서 이미지파일을 FTP에 업로드하는 방법 및 다운로드 방법이다.

다운로드시에는 Base7 인코딩 방식으로 이미지 파일을 보이게 한다.

 

파일 업로드

 

// / <summary>

// / 파일 업로드

// / </summary>

// / <returns></returns>

public ActionResult UploadFile() {

    if (Request.Files.Count > 0) {

        try {

            HttpFileCollectionBase files = Request.Files;

            HttpPostedFileBase file = files[0];

             UpLoadStream(file, "Photo");

            if (!string.IsNullOrEmpty(Request.Form["test_form"])) {

                testContext tc = new testContext();

                tc.SaveFileInfo(Request.Form["test_form"], file.FileName);

            }

            return Json("성공");

        } catch (Exception ex) {

            return Json("에러. 에러메세지:" + ex.Message);

        }

    } else {

        return Json("파일이 없습니다.");

    }

}

 

        /// <summary>

        /// FTP 업로드

        /// </summary>

        /// <param name="uploadfile"></param>

        /// <param name="subPath"></param>

        /// <returns></returns>

        public static bool UpLoadStream(HttpPostedFileBase uploadfile, string subPath)

        {

            bool bResult = false;

 

            string fileName = uploadfile.FileName;

            var fileInfo = new FileInfo(fileName);

            var FtpIp = "192.168.0.777";

            var FtpPwd = "test";

            string ftpUrl = string.Format("ftp://{0}/{1}/{2}", FtpIp, subPath, fileName);

 

            try

            {

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);

                request.Method = WebRequestMethods.Ftp.UploadFile;

 

                request.Credentials = new NetworkCredential(FtpId, FtpPwd);

                request.ContentLength = uploadfile.ContentLength;

                request.UsePassive = true;

                request.UseBinary = true;

                request.EnableSsl = false;

 

                Stream streamObj = uploadfile.InputStream;

                byte[] buffer = new byte[uploadfile.ContentLength];

                streamObj.Read(buffer, 0, buffer.Length);

                streamObj.Close();

                streamObj = null;

 

                Stream requestStream = request.GetRequestStream();

                requestStream.Write(buffer, 0, buffer.Length);

                requestStream.Flush();

                requestStream.Close();

                request = null;

 

                bResult = true;

            }

            catch (WebException ex)

            {

                throw new Exception((ex.Response as FtpWebResponse).StatusDescription);

            }

 

            return bResult;

        }

----------------------------------------------

파일 다운로드 

 

 

// / <summary>

// / 파일 다운로드

// / </summary>

// / <param name="pLotNo"></param>

// / <returns></returns>

public ActionResult DownloadFile(string pFileId) {

    testContext tc = new testContext();

    tc.GetFilesList(pFileId);

    foreach(CFiles fileInfo in tc.FilesList) {

        fileInfo.ImageString = string.Format("data:image/jpg;base64, {0}",   

        DownLoadStream("FTP_PATH/Test", fileInfo.file_id));

    }

    var jsonResult = Json(tc.FilesList, JsonRequestBehavior.AllowGet);

    jsonResult.MaxJsonLength = Int32.MaxValue;

    return jsonResult;

}

        /// <summary>

        /// FTP 다운로드

        /// </summary>

        /// <param name="subPath"></param>

        /// <param name="fileID"></param>

        /// <returns></returns>

       public static string DownLoadStream(string subPath, string fileID)

       {

           MemoryStream mem = new MemoryStream();

 

           try

           {

               var FtpIp = "192.168.0.777";

               var FtpPwd = "test";

               string ftpUrl = string.Format("ftp://{0}/{1}/{2}", FtpIp, subPath, fileID);

                              

               FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);

               request.Method = WebRequestMethods.Ftp.DownloadFile;

 

               request.Credentials = new NetworkCredential(FtpId, FtpPwd);

 

               FtpWebResponse response = (FtpWebResponse)request.GetResponse();

 

               Stream responseStream = response.GetResponseStream();                           

 

               int bufferSize = 2048;

 

               byte[] buffer = new byte[bufferSize];

 

               int bytesRead  = responseStream.Read(buffer, 0, bufferSize);

 

               while(bytesRead > 0)

               {

                   mem.Write(buffer, 0, bytesRead);

                   bytesRead = responseStream.Read(buffer, 0, bufferSize);

               }

            

               string base64 = Convert.ToBase64String(mem.ToArray());

 

               response.Close();

 

               return base64;

           }

           catch(Exception ex)

           {

               throw ex;

           }

       }

 

반응형

'IT > C#' 카테고리의 다른 글

C# 이번주 특정요일의 날짜 구하기  (0) 2020.08.13
C# MVC 세션값에 따라 화면 보이게 하는법  (0) 2020.04.01