繁体   English   中英

为什么我无法在asp.net上的服务器上找到要下载的文件?

[英]Why i can not find file on the server for download in asp.net?

我是asp.net的初学者,想编写简单的Web应用程序以使最终用户可以下载任何文件,并为此编写以下代码:

string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file = new FileInfo(filePath);
if (file.Exists) {

    Response.ContentType = "application/octet-stream";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + query[0].OstFileName.Trim());
    Response.TransmitFile(Server.MapPath("~/beh/" + query[0].OstFileName.Trim()));
    Response.End();
} else {
    Response.Write("<script>alert('File Not Found 1')</script>");
}

但是当运行该代码时,我得到其他阻止警报,意味着收到“找不到文件1”消息,这是我的错吗?

您的问题在以下几行中。

string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file = new FileInfo(filePath);

您正在为FileInfo类提供一个虚拟路径,该FileInfo无法单独映射到本地物理路径。 但是,在调用Response.TransmitFile时,您已正确地将虚拟路径映射到本地文件路径。

将您的代码更改为以下内容:

string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file - new FileInfo(Server.MapPath(filePath));

请参阅: https : //msdn.microsoft.com/zh-cn/library/ms524632(v=vs.90).aspx

字符串filePath =“〜/ beh /” +查询[0] .OstFileName;

在此行中,指定要搜索的路径,包括文件名。

您将在下一行检查此文件是否存在,如果存在,请从查询结果中保存该文件。

但是,如果在实际保存文件之前检查文件是否存在,则该文件将永远不存在。

将路径更改为:string filePath = Server.MapPath(“〜\\ beh”)。

保存文件后,将文件名添加到该文件名。

希望这是有道理的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM