2010-01-05 2 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

нормально, так что я положил Response.Write после

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

и обнаружил, что путь к файлу был направлен в папку InetPub ... так что, когда я поставил test.txt в этой папке он работал ... так что программа правильно ..

но теперь, если файл в любом другом месте на сервере, как я должен изменить программу ... Я работаю над этим, но любые предложения приветствуются

Ok я получил ответ на любой путь тоже

я удаляю server.mappath и помещаю полное местоположение вместо этого .. не знаю, почему он задавал проблемы раньше .. но теперь он работает ...

+1

Веб-приложения среднего доверия не могут обращаться к файлам за пределами пути к приложению. Возможно, попробуйте поднять права вашего приложения: http://msdn.microsoft.com/en-us/library/tkscy493.aspx Конечно, это вызывает новые проблемы с безопасностью. –

+0

, но я вхожу в систему и выдаю себя за человека ... если он не изображен, он не получит, чтобы скачать ... есть что-нибудь еще .. – user175084

4

Вы упомянули, что test.txt находится на рабочем столе сервера. Он также расположен рядом с страницей, которую вы тестируете? Попробуйте либо полностью определить путь к рабочему столу («C: \ Documents and Settings \ JohnDoe \ Desktop \ test.txt»), либо скопируйте файл, чтобы он сидел рядом с страницей .aspx.

+2

Также убедитесь, что учетная запись IIS имеет разрешение на чтение, где указанный файл прятали в. –

+0

, так что я запускаю графический интерфейс с компьютера моих клиентов, будет ли адрес местоположения файла работать ... также как мне заставить IIS читать файл .. спасибо – user175084

+1

'unknown (google)' закомментируйте проверку наличия файла, и вы увидите полный путь к файлу в своем сообщении об ошибке. –

6

Начать запись Нажмите кнопку, на которой u хотите загрузить файлы

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") 
Смежные вопросы