如何从asp.net web应用程序中选择文件夹或文件?
我有一个ASP.NET Web应用程序,我需要从网页的数据到输出文本文件。 我想让用户能够选择文件将被保存的文件夹。例如,当用户点击“浏览”按钮时,应该出现选择文件夹对话框。如何从asp.net web应用程序中选择文件夹或文件?
是否有可能在asp.net web应用程序中实现这样的事情?
感谢,
谢尔盖
编辑:
看你的评论,我想你的意思推到响应流呢?
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.";
}
}
使用<input type="file">
用户只能浏览自己的计算机上的文件。没有办法让他看到服务器上的文件夹,除非你给他一个列表或treeview结构,以便他可以选择。这是建立这种树视图的example。
很好的答案!真的有帮助! – rofans91 2012-04-02 04:04:19
谢谢。正在寻找这个。真的很有帮助。 – user1071979 2012-08-17 22:06:47
这样的下载对话框是针对特定浏览器。
查看具有Response.Write的通用处理程序,或者更好地为此目的编写Http处理程序。
不确定我需要FileUpload控件。这个控件使我能够将文件上传到服务器。我需要的是让客户端能够在他的机器上选择本地文件夹并将文件保存到此文件夹。我不需要上传文件到服务器。我需要将文件保存在本地机器的指定文件夹中 – 2010-02-20 13:22:49
已编辑的答案显示如何将文件推送到响应流。 – hearn 2010-02-20 13:37:28
感谢您的回答!那是我需要的。我能再问你一件事吗?是否可以在没有第一个窗口“打开或保存文件”的情况下显示“选择文件”对话框? – 2010-02-20 14:10:44