상세 컨텐츠

본문 제목

C# 파일업로드 모음 관련

프로그래밍 관련/웹

by AlrepondTech 2020. 9. 15. 14:02

본문

반응형

 

 

 

=================================

=================================

=================================

 

 

 

 

 

 

제목: ASP.net 2.0 파일업로드 컨드롤을 이용해 업로드 할때

글쓴이: 런닝맨

평점: 없음

조회: 936

파일업로드 컨트롤을 이용해 파일을 업로드 할때 찾아보기 버튼을 클릭하지 않고 
value(파일경로)를 자동입력 시켜서 파일업로드 할 수 있는 방법이 있나요 ?
 
아니면.. 업로드버튼 클릭 없이 페이지 로딩하면 파일을 업로드 할 수 있는 방법이 있으면
답변 부탁드립니다.
 
감사합니다.
  

 

제목: [RE] ASP.net 2.0 파일업로드 컨드롤을 이용해 업로드 할때

글쓴이: 히데

평점: 없음

조회: 1287

ASP.NET 파일업로드 컨트롤뿐만 아니라 HTML의 input을 이용하여 업로드를 할때
임의로 업로드하는건 보안상 불가능합니다.
 
보통 <input type="file"> 하나에 <input type="button">을 하나 두고
 
1. 파일업로드로 업로드할 파일을 찾고
2. 버튼을 눌러서 업로드를 실행을 하는데
 
여기서 버튼 없이 파일업로드의 찾아보기를 클릭한 후 자바스크립트를 이용하여 바로 업로드하는건 가능합니다.
하지만 '찾아보기'의 단계를 거치지 않고서는 업로드가 불가능합니다.
 
참고로 IE8에서는 보안이 강화되어 사용자가 인터넷 옵션을 변경하지 않고서는
찾아보기로 업로드한 파일의 경로(사용자의 클라이언트측 경로)를 가지고 무언가를 하는것도 불가능합니다.
예를 들어 파일업로드의 찾아보기를 통해서 사진을 올릴경우 미리보기가 불가능해집니다.

출처: http://hoons.kr/board.aspx?Name=QAASPNET&BoardIdx=25092&Page=1&Mode=2

 

 

=================================

=================================

=================================

 

 

1.      파일 다운로드

:

// 가상경로 취득
string virturePath = Request.QueryString["FilePath"];
// 물리적인 경로 취득
string realPath = Server.MapPath(virturePath);
// 버퍼를 비운다.
Response.Clear();
// 내려보낼 데이터의 형식을 지정
Response.ContentType = "Application/UnKnown";
// 파일의 타입에 상관없이 강제적으로 다운로드 창이 뜬다.
// aspx파일이 아닌 원래의 파일 이름으로 다운로드 하도록 한다.
Response.AddHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName(realPath));
// 버퍼에 바이너리 데이터를 모두 채운다.
Response.WriteFile(realPath);
// 그 데이터를 브라우저로 내려보낸다.
Response.End();

 

2.      파일 업로드

       기본적으로 ASP.NET에서 제공하는 업로드 컴포넌트는 작은 사이즈( 5M 이하) 데이터를 업로드 하는 목적으로 만들어져 있다.

       파일 업로드를 위해서 사용하는 컨트롤은 <input type =”file”>컨트롤인데, 이는 ASP.NET  컨트롤에서는 제공되지 않으며, HTML서버 컨트롤에서만 제공된다.(runet=”server” 구문 추가, 비하인드 코드에서는 서버 컨트롤만 인식이 가능하기 때문에…)

       파일을 업로드 한다는 것은 바이너리 데이터를 서버로 전송하겠다는 의미이다. 그런데, 품은 기본적으로 텍스트 데이타만 서버로 전송하게끔 설정이 되어 있다. 그러므로, 업로드를 위해서는 폼에 인코딩 타입에 대한 설정을 바꾸어 주어야 한다.

<form id=“form1” method=“Post” encType =”multipart/form-data” runat = “server”>

       파일 업로드를 위해서 사용되는 File컨트롤(이는, .NET 내부적으로는 HtmlInputFile 클래스 개체이다.) , HtmlInputFile 개체는 현재 업로드된 파일 자체를 가리키는 PostedFile속성이 있다.  속성은 업로드되는 파일 자체이며 System.Web.HttpPostedFile 클래스이다.

       예제

private void btnUpload_Click(Object sender, System.EventArgs e) { // 파일을 업로드할 경로의 지정. strPath는 현재 폴더의 물리적인 경로
    string dirPath = strPath;
    // null이면 업로드할 파일이 없다는 것이다.
    if (fileUpload.PostedFile != null) {
        try {
            string wolePath = fileUpload
                .PostedFile
                .FileName
                .Tostring();
            string fileName = Path.GetFileName(wholePath);
            // 파일이름을 그대로 할 것인지? 변경할 것인가를 선택
            그대로 사용할때 // string uniqueFilePath = Path.Combine(dirPath, fileName);
            변경 해서 사용할 때 string uniqueFilePath = GetUniqueFileNameWithPath(dirPath, fileName);
            // 현재 업로드된 데이터를 지정한 경로에 저장한다.
            fileUpload.PostedFile.SaveAs(uniqueFilePath);
            Response.Redirect("이동할 페이지");
        } catch (Exception e) {}
    }
}
private string GetUniqueFileNameWithPath(string dirPath, string fileN) {
    string fileName = fileN;
    int indexOfDot = fileName.LastIndexOf(".");
    string strName = fileName.Substring(0, indexOfDot);
    string strExt = fileName.Substring(indexOfDot + 1);
    bool bExist = true;
    int fileCount = 0;
    while (bExist) {
        if (File.Exists(Path.Combine(dirPath, fileName)) {
            fileCount ++;
            fileName = strName + "(" + fileCount + ")" + strExt;
        } else {
            bExist = false;
        }
    }
    return Path.Combine(dirPath, fileName);
}


출처: http://blog.naver.com/knulf01?Redirect=Log&logNo=40007125809


=================================

=================================

=================================

 

 

출처: http://blog.naver.com/kavange?Redirect=Log&logNo=60105451667

파일업로드 부분 -

1. 먼저 ASPX 페이지에 INPUT 을 "FILE" 타입을 만듭니다.

2. INPUIT TYPE="FILE" ID="Upfile"

 strFileName = "";
   int intFileSize = 0;
   string strBaseDir = //"c:\\Files\\";//NTFS쓰기권한
    Server.MapPath(".") + "\\";
   //넘겨져온 파일이 있다면
   if(Upfile.PostedFile != null)
   {
    //즉, 파일의 크기/파일명길이가 0보다 클때 업로드
    if(Upfile.PostedFile.ContentLength > 0
     && 
     Upfile.PostedFile.FileName.Trim().Length>0)
    {
     //[1] 파일명 구하기
     strFileName = System.IO.Path.GetFileName(Upfile.PostedFile.FileName);
     //[2] 파일사이즈 구하기
     intFileSize =  Upfile.PostedFile.ContentLength;
     //[3] 업로드(지정된 폴더)
     Response.Write(strBaseDir + strFileName);
     Upfile.PostedFile.SaveAs(strBaseDir + strFileName);//저장...
    }
   }

3. 파일업로드시 같은이름파일에(1) +1씩추가

  //[3] 업로드(지정된 폴더)
     Response.Write(strBaseDir + strFileName);
     Upfile.PostedFile.SaveAs(GetUinqueFileNameWithPath(strBaseDir, strFileName));   
    

 private string GetUinqueFileNameWithPath(
   string strBaseDirTemp,string strFileNameTemp)
  {
   int indexOfDot = strFileNameTemp.LastIndexOf(".");
   string strName = strFileNameTemp.Substring(0, indexOfDot);
   string strExt = strFileNameTemp.Substring(indexOfDot+1);

   bool blnExists = true;
   int i = 0;

   while(blnExists)
   {
    if(System.IO.File.Exists(strBaseDirTemp + strFileNameTemp))
    {
     i++;
     strFileNameTemp = strName + "(" + i + ")." + strExt;
    }
    else
    {
     blnExists = false;
    }

   }
   FileName = strFileNameTemp;                <- 파일이름명 DB에 저장시 FileName 스트링값으로 가져간다.
   return System.IO.Path.Combine(strBaseDirTemp, strFileNameTemp);
  }
 

 

파일 다운로드 부분

1. Down.aspx 페이지를 만들고 HTML상에서 맨윗부분만 빼고 모두 지워줍니다.

2. Down.aspx.cs 쪽에서 아래와 같이 코드를 입력합니다.

  public class Down : System.Web.UI.Page
 {
  string strFileName = String.Empty;//넘겨져온 파일명 저장
  string strBaseDir = String.Empty;//어디에 저장할 폴더명
  private void Page_Load(object sender, System.EventArgs e)
  {
   strFileName = Request.QueryString["FileName"].ToString();
   strBaseDir = Server.MapPath(".") + @"";
   if(strFileName == null) //넘겨져온 파일명이 없다면...
   {
    Response.End();//멈춤
   }
   else     //강제 다운로드
   {
    Response.Clear();//버퍼 비우기
    Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition","attachment;filename="+Server.UrlPathEncode(strFileName));
    Response.WriteFile(Path.Combine(strBaseDir, strFileName));
    Response.End();//버퍼 비우고, 종료.
   }
  }

   

=================================

=================================

=================================

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using Microsoft.DeepZoomTools;

namespace SmartMosaicServer.Upload {
    public class FileUploader {
        private string INPUT_DIRECTORY = "C:\\SmartMosaicServer\\input";
        // "C:\\input";
        private string OUTPUT_DIRECTORY = "C:\\SmartMosaicServer\\output";
        private string DEEPZOOM_OUTPUT_DIRECTORY = "D:\\sourcecode\\codeplex\\SmartMosaic\\SmartMosaicServer\\UploadData";
        private string DEEPZOOM_URL = "http://211.189.20.163/SmartMosaicServer/UploadData/";
        private const string UPLOAD_FOLDER = "c:\\uploadfile\\";
        // / <summary>
        // / 이미지를 업로드 한 후 저장된 파일 경로를 반환한다.
        // / </summary>
        // / <param name="FileUp">업로드 컨트롤</param>
        // / <returns></returns>
        public string ImageUpload2(FileUpload FileUp, int themeCode) {
            string savedDir = "D:\\sourcecode\\codeplex\\SmartMosaic\\

            SmartMosaicServer\\UploadData\\index.txt ";

            int USER_COUNT = 0;
            lock(GetType()) {
                if (!File.Exists(savedDir)) {
                    FileStream fs = File.Create(savedDir);
                    fs.Close();
                    fs.Dispose();
                }
                StreamReader sr = File.OpenText(savedDir);
                USER_COUNT = Convert.ToInt32(sr.ReadLine());
                USER_COUNT ++;
                sr.Close();
                sr.Dispose();
                File.WriteAllText(savedDir, USER_COUNT.ToString());
            }
            // the byte array argument contains the content of the file
            // the string argument contains the name and extension
            // of the file passed in the byte array
            string newInputFileName = USER_COUNT + "" + themeCode + ".jpg";
            string newOutputFileName = USER_COUNT + ".jpg";
            string endOutputFileName = USER_COUNT + ".dat";
            FileUp.PostedFile.SaveAs(INPUT_DIRECTORY + "\\" + newInputFileName);
            // // instance a memory stream and pass the
            // // byte array to its constructor
            // MemoryStream ms = new MemoryStream(file);
            // instance a filestream pointing to the
            // storage folder, use the original file name
            // to name the resulting file
            // FileStream fs = new FileStream
            //    (INPUT_DIRECTORY + "\\" + newInputFileName, FileMode.Create);
            // write the memory stream containing the original
            // file as a byte array to the filestream
            // ms.WriteTo(fs);
            // // clean up
            // ms.Close();
            // fs.Close();
            // fs.Dispose();
            // 여기서 파일 모니터하면 된다.
            while (!File.Exists(OUTPUT_DIRECTORY + "\\" + endOutputFileName)) { // 1초에 한번씩 체크
                System
                    .Threading
                    .Thread
                    .Sleep(1000);
            }
            // 파일이 생성된 경우
            // DeepZoomAPI 수행
            ImageCreator creator = new ImageCreator();
            creator.TileSize = 256;
            creator.TileFormat = Microsoft
                .DeepZoomTools
                .ImageFormat
                .Jpg;
            creator.CopyMetadata = false;
            creator.Create(OUTPUT_DIRECTORY + "\\" + newOutputFileName, DEEPZOOM_OUTPUT_DIRECTORY + "\\" + USER_COUNT + "\\dzc_output.xml");
            // UploadResult result = new UploadResult()
            // {
            //    UploadResultCode = UploadResultCodeEnum.Success,
            //    Detail = (DEEPZOOM_URL + USER_COUNT)
            // };
            // return OK if we made it this far
            return DEEPZOOM_URL + USER_COUNT;
            // string ret = "";        // 반환할 문자열
            // string upDir = "";      // 업로드할 파일 저장 위치
            // string fName = "";      // 업로드된 실제 파일명
            // string fFullName = "";  // 저장할 파일의 풀 경로
            // string fExt = "";       // 파일의 확장자명
            // string fRealName = "";  // 파일의 확장자를 뺀 실제 파일명
            // string newFileName = "";// 새로 만들어질 파일명
            // int findex = 0; // 파일의 인덱스번호
            // System.IO.DirectoryInfo di = null;
            // System.IO.FileInfo fInfo = null;
            // // 파일이 있나?
            // if (FileUp.HasFile == true)
            // {
            //    // 저장할 경로
            //    upDir = UPLOAD_FOLDER;
            //    // 경로에 디렉토리가 없으면 만든다.
            //    di = new System.IO.DirectoryInfo(upDir); // 디렉토리를 다룰 연장
            //    if (di.Exists == false)
            //        di.Create();
            //    // 업로드 된 파일을 가지고 저장할 파일의 풀 경로를 만들어낸다.
            //    fName = FileUp.FileName;
            //    fFullName = upDir + fName;
            //    fInfo = new System.IO.FileInfo(fFullName); // 파일을 다룰 연장
            //    // 이미 해당하는 파일이 있으면
            //    if (fInfo.Exists == true)
            //    {
            //        fExt = fInfo.Extension;
            //        fRealName = fName.Replace(fExt, "");
            //        // 루프를 돌면서 실제 저장될 파일명을 결정한다.
            //        do
            //        {
            //            findex++;
            //            newFileName = fRealName + "_" + findex.ToString() + fExt;
            //            fInfo = new System.IO.FileInfo(upDir + newFileName);
            //        } while (fInfo.Exists);
            //        fFullName = upDir + newFileName;
            //        fName = newFileName;
            //    }
            //    FileUp.PostedFile.SaveAs(fFullName);
            //    fInfo = new System.IO.FileInfo(fFullName);
            //    ret = "../upload/" + fName;
            // }
            // return ret;
        }
        /*
         * public UploadResult UploadFile(byte[] file, string fileName, int themeCode)
        {
            string savedDir = "D:\\sourcecode\\codeplex\\SmartMosaic\\SmartMosaicServer\\UploadData\\index.txt";

            int USER_COUNT = 0;

            lock(GetType()) 
            {
                if (!File.Exists(savedDir))
                {
                    FileStream fs = File.Create(savedDir);

                    fs.Close();
                    fs.Dispose();
                }

                StreamReader sr = File.OpenText(savedDir);

                USER_COUNT = Convert.ToInt32(sr.ReadLine());
                USER_COUNT++;

                sr.Close();
                sr.Dispose();

                File.WriteAllText(savedDir, USER_COUNT.ToString());
            }

            // the byte array argument contains the content of the file
            // the string argument contains the name and extension
            // of the file passed in the byte array
            try
            {
                string newInputFileName = USER_COUNT + "" + themeCode + ".jpg";
                string newOutputFileName = USER_COUNT + ".jpg";
                string endOutputFileName = USER_COUNT + ".dat";

                // instance a memory stream and pass the
                // byte array to its constructor
                MemoryStream ms = new MemoryStream(file);

                // instance a filestream pointing to the 
                // storage folder, use the original file name
                // to name the resulting file
                FileStream fs = new FileStream
                    (INPUT_DIRECTORY + "\\" + newInputFileName, FileMode.Create);

                // write the memory stream containing the original
                // file as a byte array to the filestream
                ms.WriteTo(fs);

                // clean up
                ms.Close();
                fs.Close();
                fs.Dispose();

                // 여기서 파일 모니터하면 된다.
                while (!File.Exists(OUTPUT_DIRECTORY + "\\" + endOutputFileName))
                {
                    // 1초에 한번씩 체크
                    System.Threading.Thread.Sleep(1000);
                }
                
                // 파일이 생성된 경우
                // DeepZoomAPI 수행
                ImageCreator creator = new ImageCreator();
                creator.TileSize = 256;
                creator.TileFormat = Microsoft.DeepZoomTools.ImageFormat.Jpg;

                creator.CopyMetadata = false;
                creator.Create(OUTPUT_DIRECTORY + "\\" + newOutputFileName,
                    DEEPZOOM_OUTPUT_DIRECTORY + "\\" + USER_COUNT + "\\dzc_output.xml");

                UploadResult result = new UploadResult()
                {
                    UploadResultCode = UploadResultCodeEnum.Success,
                    Detail = (DEEPZOOM_URL + USER_COUNT)
                };

                // return OK if we made it this far
                return result;
            }
            catch (Exception ex)
            {
                // return the error message if the operation fails
                return new UploadResult()
                {
                    UploadResultCode = UploadResultCodeEnum.Fail,
                    Detail = ex.Message.ToString()
                }; ;
            }
        }
         */
        // / <summary>
        // / 이미지를 업로드 한 후 저장된 파일 경로를 반환한다.
        // / </summary>
        // / <param name="FileUp">업로드 컨트롤</param>
        // / <returns></returns>
        public string ImageUpload(FileUpload FileUp) {
            string ret = ""; // 반환할 문자열
            string upDir = ""; // 업로드할 파일 저장 위치
            string fName = ""; // 업로드된 실제 파일명
            string fFullName = ""; // 저장할 파일의 풀 경로
            string fExt = ""; // 파일의 확장자명
            string fRealName = ""; // 파일의 확장자를 뺀 실제 파일명
            string newFileName = ""; // 새로 만들어질 파일명
            int findex = 0; // 파일의 인덱스번호
            System.IO.DirectoryInfo di = null;
            System.IO.FileInfo fInfo = null;
            // 파일이 있나?
            if (FileUp.HasFile == true) { // 저장할 경로
                upDir = UPLOAD_FOLDER;
                // 경로에 디렉토리가 없으면 만든다.
                di = new System.IO.DirectoryInfo(upDir); // 디렉토리를 다룰 연장
                if (di.Exists == false) 
                    di.Create();
                
                // 업로드 된 파일을 가지고 저장할 파일의 풀 경로를 만들어낸다.
                fName = FileUp.FileName;
                fFullName = upDir + fName;
                fInfo = new System.IO.FileInfo(fFullName);
                // 파일을 다룰 연장
                // 이미 해당하는 파일이 있으면
                if (fInfo.Exists == true) {
                    fExt = fInfo.Extension;
                    fRealName = fName.Replace(fExt, "");
                    // 루프를 돌면서 실제 저장될 파일명을 결정한다.
                    do {
                        findex ++;
                        newFileName = fRealName + "_" + findex.ToString() + fExt;
                        fInfo = new System.IO.FileInfo(upDir + newFileName);
                    } while (fInfo.Exists);
                    fFullName = upDir + newFileName;
                    fName = newFileName;
                }
                FileUp.PostedFile.SaveAs(fFullName);
                fInfo = new System.IO.FileInfo(fFullName);
                ret = "../upload/" + fName;
            }
            return ret;
        }
    }
}

 

 

 

반응형

 

728x90



출처: http://blog.naver.com/PostView.nhn?blogId=doghole&logNo=100100033856


 

=================================

=================================

=================================

 

 

 

 http://ki3ki7.blog.me/80119615168 

Response.TransmitFile(FilePath); <-대용량 파일 다운로드의 경우 메모리 버퍼보다 TransmitFile이 더 낫다.

----------------------------------------------------------------------------------------------------------------------------
length = iStream.Read(buffer, 0, 10000);

// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);

// Flush the data to the HTML output.
Response.Flush();

----------------------------------------------------------------------------------------------------------------------------
http://www.aspsnippets.com/Articles/Save-and-Retrieve-Files-from-SQL-Server-Database-using-ASP.Net.aspx<-주로 참고한 곳


1.http://www.aspheute.com/english/20000802.asp

2.http://msdn.microsoft.com/en-us/library/aa479405.aspx

3.http://www.developer.com/net/asp/article.php/3097661



=================================

=================================

=================================

 

 

protected void btn_reg_Click(object sender, EventArgs e) {
    // HttpFileCollection 클래스는 클라이언트가 업로드한 파일에 대한 액세스를 제공하고 그 파일을 구성한다.
    // input type이 file로 된것은 다 가져오는것 같다 (2개 이상일 경우 배열로 받는다)
    // 자세한 내용은 http://msdn.microsoft.com/ko-kr/library/system.web.httpfilecollection(VS.90).aspx 링크 참조
    HttpFileCollection addFile = HttpContext
        .Current
        .Request
        .Files;
    // 먼저 업로드 갯수만큼 돌면서 파일 확장자, 사이즈, 파일명중복 등 체크 한다.
    for (int i = 0; i < addFile.Count; i ++) { /* 파일의 각종 정보 획득
Response.Write(addFile[i].ContentLength // 파일 사이즈
+ " / " + addFile[i].ContentType //타입
+ " / " + addFile[i].FileName // 파일명
+ " / " + fileExt //파일 확장자
+ " / " + addFile[i].GetType().ToString() + "<br>");
*/
        string fileExt = System
            .IO
            .Path
            .GetExtension(addFile[i].FileName); // 확장자 구한다(점[.]까지 포함된다).
        if (addFile[i].ContentLength > 1024 * 1024 * 10) { // 파일 용량이 클때
            Response.Write("용량 초과");
            Response.End();
        } else if (fileExt == ".asp" || fileExt == ".aspx" || fileExt == ".php") { // 확장자체크
            Response.Write("허용불가한 파일");
            Response.End();
        }
    }
    String savePath = Server.MapPath("/") + "Board\\UploadFile\\";
    // 저장될 경로 설정.
    /* 아래 소스는 HttpPostedFile 클래스를 한번더 사용해서 처리 하는 방식
for (int i = 0; i < addFile.Count; i++)
{
// HttpPostedFile 클래스는 클라이언트에서 업로드한 개별 파일에 액세스할 수 있도록 한다.
// 자세한 내용은 http://msdn.microsoft.com/ko-kr/library/system.web.httppostedfile(v=VS.90).aspx 링크 참조

HttpPostedFile postedFile = addFile[i];
if (postedFile.ContentLength > 0) // 파일이 있으면
{
//Response.Write(GetUniqueFileName(savePath, addFile[i].FileName)); 
postedFile.SaveAs(GetUniqueFileName(savePath, postedFile.FileName)); // 최종 저장
}
}
*/
    // HttpPostedFile를 사용하지 않아도 되는것 같아서 빼고 처리
    string fileWholePath;
    string[] strFileName = new string[3]; // 파일 갯수 만큼 배열변수 선언 파일 이름과 사이즈 DB에 넣기 위함
    string[] strFileSize = new string[3];
    for (int i = 0; i < addFile.Count; i ++) {
        if (addFile[i].ContentLength > 0) {
            // 파일이 있으면
            // Response.Write(GetUniqueFileName(savePath, addFile[i].FileName));
            fileWholePath = GetUniqueFileName(savePath, addFile[i].FileName); // 유니크한 파일명 구함
            strFileName[i] = fileWholePath.Substring(fileWholePath.LastIndexOf("\\") + 1); // 전체경로에서 파일명 구함
            strFileSize[i] = addFile[i].ContentLength.ToString(); // 사이즈 구함
            addFile[i].SaveAs(fileWholePath); // 최종 저장}
        }
        // [주의] 기본적으로 파일 용량이 4M 이상일 경우 업로드 안된다.
        // 용량을 늘리고 싶은 경우 web.config에서 설정변경 가능하다.
        // 한가지 주의 할것은 설정한 용량보다 큰 파일이 들어올 경우 프로그램에서 체크 로직을 만나기 전에 에러가 난다.
        // 그래서 에러를 피하기 위해서는 설정을 좀 넉넉히 잡아 주고 위에서 처럼 프로그램에서 체크를 하고 메세지를 띄어 줘야 한다.
        /* 아래는 개별 파일에 대한 접근(즉 컨트롤 ID(addFile)로 개별 파일로 접근할수 있다.)
업로드 갯수가 여러개인 경우 불편할것 같음
if (addFile.PostedFile.ContentLength > (1024 * 1024 * 10)) 
{
Response.Write("파일 용량 초과");
Response.End();
}
else
{
if ((addFile.PostedFile != null) && (addFile.PostedFile.ContentLength > 0))
{
Response.Write(addFile.PostedFile.ContentLength);
string fn = System.IO.Path.GetFileName(addFile.PostedFile.FileName);
string SaveLocation = Server.MapPath("/") + "\\Board\\UploadFile\\" + fn ;
try
{
addFile.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
else
{
Response.Write("Please select a file to upload.");
}
}
*/
    }
    // 파일 중복확인하고 유니크한 파일명 얻기
    // 디렉토리 경로와 파일명을 인자로 받는다.
    private string GetUniqueFileName(string dirPath, string fileName) {
        string fExt = System
            .IO
            .Path
            .GetExtension(fileName); // 파일확장자 구함(점[.] 까지 포함된다)
        string fName = fileName.Substring(0, fileName.IndexOf(fExt)); // 파일명 구함
        bool bExist = true;
        int countFileName = 0; // 동일 파일명이 존재할경우 뒤에 붙일 숫자
        while (bExist) {
            if (System
                    .IO
                    .File
                    .Exists(Path.Combine(dirPath, fileName))) { // 동일 파일명이 있으면
                countFileName ++;
                fileName = fName + "(" + countFileName + ")" + fExt; // 숫자를 붙여 유니크한 파일명을 만든다.
            } else { // 동일 파일명이 없으면 루프를 빠져 나오기 위해 bExist 값을 false로 설정
                bExist = false;
            }
        }
        return Path.Combine(dirPath, fileName); // 저장될 파일의 전체 경로를 리턴
    }

[출처] [ASP.NET] 파일 업로드, 다중 파일 업로드|작성자 깜보

 

 

=================================

=================================

=================================

 

 

Hi,

 I am uploading a file and retriving the same with "HttpFileCollection" and writing to a specified path.

I need information about, where the file actually resides before i write it to the path.

If the File resides in webserver memory, is there a way to clear it off immediately as soon as the file is written to the path.

Here is my code:

public static void SavePostedFile(HttpFileCollection PostedFiles, string FolderPath, string Filename, out string RetnMsg) {
    try { // Loop over the uploaded files and save to disk.
        int i;
        for (i = 0; i < PostedFiles.Count; i ++) {
            HttpPostedFile postedFile = PostedFiles[i];
            // Access the uploaded file's content in-memory:
            System.IO.Stream inStream = postedFile.InputStream;
            byte[] fileData = new byte[postedFile.ContentLength];
            inStream.Read(fileData, 0, postedFile.ContentLength);
            // Save the posted file in our "data" virtual directory.
            postedFile.SaveAs(FolderPath + "\\" + Filename);
        }
        RetnMsg = "Successful";
    } catch (Exception ex) {
        RetnMsg = ex.ToString();
    }
}

 

 

=================================

=================================

=================================

 

 

 

반응형


관련글 더보기

댓글 영역