如何在ASP.NET Web应用程序中选择文件夹或文件?

6

我有一个ASP.NET Web应用程序,需要将网页数据输出到文本文件中。

我想让用户能够选择要保存文件的文件夹。例如,当用户单击“浏览”按钮时,应该出现选择文件夹对话框。

ASP.NET Web应用程序是否可以实现这样的功能?

3个回答

3

使用<input type="file">,用户只能浏览他电脑上的文件。如果你不提供一个列表或树形结构,让用户从中选择,他将无法看到服务器上的文件夹。以下是一个构建这样一种树形结构的示例


2
编辑:
根据您的评论,我认为您的意思是将其推送到响应流中?
 protected void lnbDownloadFile_Click(object sender, EventArgs e)
 {
  String YourFilepath;
  System.IO.FileInfo file = 
  new System.IO.FileInfo(YourFilepath); // full file path on disk
  Response.ClearContent(); // neded to clear previous (if any) written content
  Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
  Response.AddHeader("Content-Length", file.Length.ToString());
  Response.ContentType = "text/plain";
  Response.TransmitFile(file.FullName);
  Response.End();
 }

这应该会在浏览器中显示一个对话框,让用户选择要保存文件的位置。
你想要使用FileUpload控件。 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.aspx
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.";
    }

  }

1
不确定我是否需要FileUpload控件。这个控件让我能够将文件上传到服务器。我需要的是给客户端一个选择本地文件夹并将文件保存到该文件夹的能力。我不需要将文件上传到服务器,而是需要将文件保存在本地机器指定的文件夹中。 - Sergey Smelov
修改答案以展示如何将文件推送到响应流。 - hearn
谢谢你的回答!那正是我需要的。我能再问你一件事吗?是否有可能在没有第一个窗口“打开或保存文件”的情况下显示“选择文件”对话框? - Sergey Smelov
你在打开/保存对话框中看到的内容取决于浏览器的实现,但出于安全原因,你的应用程序不能修改此对话框。 - hearn

1

这种下载对话框是与浏览器有关的。

可以查看使用 Response.Write 的通用处理程序,或者更好地编写一个 Http 处理程序来实现此目的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接