asp.net ищет файл - PullRequest
       2

asp.net ищет файл

0 голосов
/ 24 марта 2012

У меня есть метод на моей веб-странице asp.net, чтобы выгрузить файл csv в мой gridview, но я хотел включить диалоговое окно, чтобы пользователь мог просмотреть и выбрать файл csv со своего ПК, чтобы импортировать и захватить это имя файла и информация о пути для подачи в мой метод импорта CSV, чтобы он мог воздействовать на файл. Есть ли простой способ сделать это?

Ответы [ 2 ]

0 голосов
/ 24 марта 2012

Пока что все здесь кажутся правильными в своих ответах. Еще один вариант - использовать элемент управления ASP.NET FileUpload , если вы хотите придерживаться серверных элементов управления.

Вот пример того, как использовать элемент управления, который я бессовестно украл из здесь :

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<script runat="server">

  protected void UploadButton_Click(object sender, EventArgs e)
  {
    // Specify the path on the server to
    // save the uploaded file to.
    String savePath = @"c:\temp\uploads\";

    // Before attempting to perform operations
    // on the file, verify that the FileUpload 
    // control contains a file.
    if (FileUpload1.HasFile)
    {
      // Get the name of the file to upload.
      String fileName = FileUpload1.FileName;

      // Append the name of the file to upload to the path.
      savePath += fileName;


      // Call the SaveAs method to save the 
      // uploaded file to the specified path.
      // This example does not perform all
      // the necessary error checking.               
      // If a file with the same name
      // already exists in the specified path,  
      // the uploaded file overwrites it.
      FileUpload1.SaveAs(savePath);

      // Notify the user of the name of the file
      // was saved under.
      UploadStatusLabel.Text = "Your file was saved as " + fileName;
    }
    else
    {      
      // Notify the user that a file was not uploaded.
      UploadStatusLabel.Text = "You did not specify a file to upload.";
    }

  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>FileUpload Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <h4>Select a file to upload:</h4>

       <asp:FileUpload id="FileUpload1"                 
           runat="server">
       </asp:FileUpload>

       <br /><br />

       <asp:Button id="UploadButton" 
           Text="Upload file"
           OnClick="UploadButton_Click"
           runat="server">
       </asp:Button>    

       <hr />

       <asp:Label id="UploadStatusLabel"
           runat="server">
       </asp:Label>        
    </div>
    </form>
</body>
</html>
0 голосов
/ 24 марта 2012

Вам нужен этот класс System.Web.UI.HtmlControls.HtmlInputFile

Из MSDN:

Используйте серверный элемент управления HtmlInputFile для обработки загрузки двоичных или текстовых файлов из клиента браузерана сервер.Загрузка файла работает с Microsoft Internet Explorer версии 3.02 или более поздней.

ОБНОВЛЕНИЕ: Вот пример рабочего кода из MSDN (.net v1.1)

<%@ Page Language="VB" AutoEventWireup="True" %>

<html>
 <head>

    <script language="VB" runat="server">
       Sub Button1_Click(Source As Object, e As EventArgs)

            If Text1.Value = "" Then
                Span1.InnerHtml = "Error: you must enter a file name"
                Return
            End If

            If Not (File1.PostedFile Is Nothing) Then
                Try
                    File1.PostedFile.SaveAs(("c:\temp\" & Text1.Value))
                    Span1.InnerHtml = "File uploaded successfully to <b>c:\temp\" & _
                                      Text1.Value & "</b> on the Web server"
                Catch exc As Exception
                    Span1.InnerHtml = "Error saving file <b>c:\temp\" & _
                                      Text1.Value & "</b><br>" & exc.ToString()
                End Try
            End If
        End Sub 'Button1_Click 
    </script>

 </head>
 <body>

    <h3>HtmlInputFile Sample</h3>

    <form enctype="multipart/form-data" runat="server">

       Select File to Upload: 
       <input id="File1" 
              type="file" 
              runat="server">

       <p>
       Save as filename (no path): 
       <input id="Text1" 
              type="text" 
              runat="server">

       <p>
       <span id=Span1 
             style="font: 8pt verdana;" 
             runat="server" />

       <p>
       <input type=button 
              id="Button1" 
              value="Upload" 
              OnServerClick="Button1_Click" 
              runat="server">

    </form>

 </body>
 </html>
...