2010-01-05 8 views
1

서버에서 로컬 호스트로 파일을 다운로드하고 싶습니다.서버 asp.net에서 파일 다운로드

은 내가 작업을해야하지만, 버튼을 로컬 호스트 컴퓨터로 서버에서 다운로드해야 할 파일을 클릭 지금

 protected void Button4_Click(object sender, EventArgs e) 
    { 
    //To Get the physical Path of the file(test.txt) 
    string filepath = Server.MapPath("test.txt"); 

    // Create New instance of FileInfo class to get the properties of the file being downloaded 
    FileInfo myfile = new FileInfo(filepath); 

    // Checking if file exists 
    if (myfile.Exists) 
    { 
    // Clear the content of the response 
    Response.ClearContent(); 

// Add the file name and attachment, which will force the open/cancel/save dialog box to show, to the header 
Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name); 

// Add the file size into the response header 
Response.AddHeader("Content-Length", myfile.Length.ToString()); 

// Set the ContentType 
Response.ContentType = ReturnExtension(myfile.Extension.ToLower()); 

// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead) 
Response.TransmitFile(myfile.FullName); 

// End the response 
Response.End(); 
    } 

    } 

    private string ReturnExtension(string fileExtension) 
    { 
     switch (fileExtension) 
     { 
      case ".htm": 
      case ".html": 
      case ".log": 
       return "text/HTML"; 
      case ".txt": 
       return "text/plain"; 
      case ".doc": 
       return "application/ms-word"; 
      case ".tiff": 
      case ".tif": 
       return "image/tiff"; 
      case ".asf": 
       return "video/x-ms-asf"; 
      case ".avi": 
       return "video/avi"; 
      case ".zip": 
       return "application/zip"; 
      case ".xls": 
      case ".csv": 
       return "application/vnd.ms-excel"; 
      case ".gif": 
       return "image/gif"; 
      case ".jpg": 
      case "jpeg": 
       return "image/jpeg"; 
      case ".bmp": 
       return "image/bmp"; 
      case ".wav": 
       return "audio/wav"; 
      case ".mp3": 
       return "audio/mpeg3"; 
      case ".mpg": 
      case "mpeg": 
       return "video/mpeg"; 
      case ".rtf": 
       return "application/rtf"; 
      case ".asp": 
       return "text/asp"; 
      case ".pdf": 
       return "application/pdf"; 
      case ".fdf": 
       return "application/vnd.fdf"; 
      case ".ppt": 
       return "application/mspowerpoint"; 
      case ".dwg": 
       return "image/vnd.dwg"; 
      case ".msg": 
       return "application/msoutlook"; 
      case ".xml": 
      case ".sdxl": 
       return "application/xml"; 
      case ".xdp": 
       return "application/vnd.adobe.xdp+xml"; 
      default: 
       return "application/octet-stream"; 
     } 
    } 

를 작동하지 않는 인터넷에서 코드를 가지고 ...하지만 아무것도 보이지 않는다

내가이 세 레르 족의 바탕 화면에있는 test.txt이 ... 일이 될 ... 저장 파일 옵션은

나는 파일을 게시 .. 클라이언트 측에서 와서 넣어하지 않습니다 서버의 inetpub 폴더에 있고 클라이언트에서 GUI를 실행하십시오. 면은 ... 모든 것을 대신 내가 내 모든 위치에서 다운로드 할 ...

제안

이 ...는 Inetpub 폴더에있는 경우이 프로그램은 파일을 다운로드

도와주세요 ...이를 제외하고 작동 서버 ...

??

답변

-1

는 그래서 난

string filepath = Server.MapPath("test.txt"); 

후 Response.Write를 넣어 해당 파일 경로가 내가이 일을 해당 폴더에있는 test.txt을 넣어 너무 때 ... Inetpub 폴더를 가리키는 것을 발견했다 ... 그래서 프로그램은 맞다 ..

하지만 지금은 파일이 내가 그것을하고 있어요 ... 프로그램을 수정하지만, 어떤 제안은 내가있어 환영

괜찮아 방법을 서버에서 다른 위치 인 경우 모든 경로에 대한 답변도

나는 server.mappath를 제거하고 대신 전체 위치를 지정합니다 .. 왜 이전에 문제가 있었는지는 모르지만 지금은 작동 중입니다 ...

+1

보통 신뢰 웹 응용 프로그램은 응용 프로그램 경로 외부의 파일에 액세스 할 수 없습니다. 아마도 앱의 권한을 높이는 것이 좋습니다. http://msdn.microsoft.com/ko-kr/library/tkscy493.aspx 물론, 이는 새로운 보안 문제를 야기합니다. –

+0

하지만 로그인 중이며 사용자를 가장 한 경우 ... 가장하지 않은 경우 다운로드하지 않을 것입니다. 다른 것이 있습니다. – user175084

4

당신은 test.txt가 서버의 바탕 화면에 있다고 언급합니다. 테스트중인 페이지 바로 옆에도 있습니까? 바탕 화면의 경로 ("C : \ Documents and Settings \ JohnDoe \ Desktop \ test.txt")를 완전히 정규화하거나 .aspx 페이지 옆에 파일을 복사 해보십시오. 확인

+2

또한 IIS 계정이 파일에 은닉되어있는 것을 어디든지 읽을 수있는 권한이 있는지 확인하십시오. –

+0

그래서 내 클라이언트 컴퓨터에서 GUI를 실행하는 파일 작업의 위치 주소입니다 ... 어떻게 내가 IIS를 파일을 읽을 수 있도록 ... 덕분에 – user175084

+1

'알 수없는 (구글) '파일 존재 체크 아웃 코멘트, 오류 메시지에 파일 전체 경로가 표시됩니다. –

6

쓰기 버튼을 클릭하십시오. 파일을 다운로드하고 싶은 곳을 클릭하십시오.

protected void Button1_Click(object sender, EventArgs e) 

{ 

     string allowedExtensions = ".mp4,.pdf,.m4v,.gif,.jpg,.png,.swf,.css,.htm,.html,.txt"; 
     // edit this list to allow file types - do not allow sensitive file types like .cs or .config 

     string fileName = "Images/apple.jpg"; 
     string filePath = ""; 

     //if (Request.QueryString["file"] != null) fileName = Request.QueryString["file"].ToString(); 
     //if (Request.QueryString["path"] != null) filePath = Request.QueryString["path"].ToString(); 

     if (fileName != "" && fileName.IndexOf(".") > 0) 
     { 
      bool extensionAllowed = false; 
      // get file extension 
      string fileExtension = fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.')); 

      // check that we are allowed to download this file extension 
      string[] extensions = allowedExtensions.Split(','); 
      for (int a = 0; a < extensions.Length; a++) 
      { 
       if (extensions[a] == fileExtension) 
       { 
        extensionAllowed = true; 
        break; 
       } 
      } 

      if (extensionAllowed) 
      { 
       // check to see that the file exists 
       if (File.Exists(Server.MapPath(filePath + '/' + fileName))) 
       { 

        // for iphones and ipads, this script can cause problems - especially when trying to view videos, so we will redirect to file if on iphone/ipad 
        // if (Request.UserAgent.ToLower().Contains("iphone") || Request.UserAgent.ToLower().Contains("ipad")) { Response.Redirect(filePath + '/' + fileName); } 
        Response.Clear(); 
        Response.AddHeader("content-disposition", "attachment;filename=" + fileName); 
        Response.WriteFile(Server.MapPath(filePath + '/' + fileName)); 
        Response.End(); 
       } 
       else 
       { 
        litMessage.Text = "File could not be found"; 
       } 
      } 
      else 
      { 
       litMessage.Text = "File extension is not allowed"; 
      } 
     } 
     else 
     { 
      litMessage.Text = "Error - no file to download"; 
     } 
    } 
0

당신은 당신의 위치에 폴더를 변경할 수 있습니다

Directory.SetCurrentDirectory(HttpContext.Current.Server.MapPath("~ your path in here")