我有一个String变量(在C#中),它包含我服务器上PDF文件的完整路径 (就像“〜/ doc / help.pdf”)。
我希望在点击按钮时,此文件将下载到客户端计算机。
我创建了一个按钮并在C#中创建了onClick事件。现在,我应该编写哪些代码来执行此操作?
答案 0 :(得分:15)
我认为你正在寻找类似的东西。
private void Button1_click(object sender, System.EventArgs e)
{
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=help.pdf");
Response.TransmitFile(Server.MapPath("~/doc/help.pdf"));
Response.End();
}
答案 1 :(得分:2)
在btn_Click
:
Response.Redirect("~/doc/link.pdf");
答案 2 :(得分:1)
我建议将以下内容放入您的按钮点击事件代码中。
这将为用户提供下载文件的弹出窗口。我已经彻底测试过并在生产代码中使用它。
void btnDownloadFile_Click(object sender, EventArgs e)
{
string strLocalFilePath = "~/doc/help.pdf";
string fileName = "help.pdf";
Response.Clear();
Stream iStream = null;
const int bufferSize = 64 * 1024;
byte[] buffer = new Byte[bufferSize];
int length;
long dataToRead;
try
{
iStream = new FileStream(strLocalFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
dataToRead = iStream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
while (dataToRead > 0)
{
if (Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, bufferSize);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
buffer = new byte[bufferSize];
dataToRead = dataToRead - length;
}
else
{
//prevent infinate loop on disconnect
dataToRead = -1;
}
}
}
catch (Exception ex)
{
//Your exception handling here
}
finally
{
if (iStream != null)
{
iStream.Close();
}
Response.Close();
}
}
答案 3 :(得分:0)
使用ASP按钮:
button.OnClientClick = string.Format("javascript:window.location='{0}'", pdfLink);
这背后的逻辑是:Client-side click
这不会重新加载页面并进行回复,它只会导航到将在浏览器中显示的PDF。
将按钮的onclick事件设置为此scriptlet:
onclick="javascript:window.location='/doc/help.pdf'"
创建服务器端:
<input type="button" onclick="javascript:window.location='<%=PDFLink %>'" />
其中PDFLink是后面代码中的字符串属性:
public string PDFLink
{
get
{
return "/doc/link.pdf";
}
}
从这里开始,从数据库中获取字符串并在需要时将其呈现为绝对值应该是微不足道的。
答案 4 :(得分:0)
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=File_Name.pdf");
Response.TransmitFile(Server.MapPath("Folder_Name/File_Name.pdf"));
Response.End();
答案 5 :(得分:0)
string path;
string filename = "Page-3" + ".Pdf";
path = "~/H/Emp/" + filename.ToString();
Response.ContentType = "image/jpg";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename.ToString());
Response.TransmitFile(Server.MapPath(path));
Response.End();