在我的 Asp 页面中,我必须在下载 asp 页面中的文件之前调用一个 javascript 函数。我的实际要求是每次单击下载按钮时都必须确保下载格式。
所以,在我的下载按钮事件中,我只显示一个包含两个单选按钮(asp:RadioButton)的 div 标签,即 docx、pdf 和一个 OK 按钮。选择任何单选按钮后,用户将按下 ok 按钮(asp:Button) .
最后,
在 Ok Button(asp:Button) 事件中,我只是隐藏了 div 标签部分,并且基于用户选择的输出格式,文件将被下载。
我的确定按钮事件代码如下:
protected void OKButton(object sender, EventArgs e)
{
string outputType = "";
if (docx.Checked == true)
{
outputType = "docx";
}
else
{
outputType = "pdf";
}
filename=filename+"."+outputType;
ClientScript.RegisterStartupScript(GetType(), "popup", "hidePopUp()", true);
bool isDownloaded=downloadFile(strURL, docPath, filename);
}
downloadFile 函数如下:
protected bool downloadFile(string srcURL, string docPath, string filenameOnly)
{
System.IO.FileInfo FileName = new System.IO.FileInfo(srcURL);
FileStream myFile = new FileStream(srcURL, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader _BinaryReader = new BinaryReader(myFile);
if (FileName.Exists)
{
try
{
long startBytes = 0;
string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(docPath).ToString("r");
string _EncodedData = HttpUtility.UrlEncode(filenameOnly, Encoding.UTF8) + lastUpdateTiemStamp;
Response.Clear();
Response.Buffer = false;
Response.AddHeader("Accept-Ranges", "bytes");
Response.AppendHeader("ETag", "\"" + _EncodedData + "\"");
Response.AppendHeader("Last-Modified", lastUpdateTiemStamp);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName.Name);
Response.AddHeader("Content-Length", (FileName.Length - startBytes).ToString());
Response.AddHeader("Connection", "Keep-Alive");
Response.ContentEncoding = Encoding.UTF8;
//Send data
_BinaryReader.BaseStream.Seek(startBytes, SeekOrigin.Begin);
//Dividing the data in 1024 bytes package
int maxCount = (int)Math.Ceiling((FileName.Length - startBytes + 0.0) / 1024);
//Download in block of 1024 bytes
int i;
for (i = 0; i < maxCount && Response.IsClientConnected; i++)
{
Response.BinaryWrite(_BinaryReader.ReadBytes(1024));
Response.Flush();
}
//if blocks transfered not equals total number of blocks
if (i < maxCount)
return false;
return true;
}
catch (Exception ex)
{
return false;
}
finally
{
_BinaryReader.Close();
myFile.Close();
}
}
else
{
return false;
}
}//downloadFile ends here...
至此,特定文件下载成功。但它并没有隐藏 Div Tag 部分。
我尝试不调用 downloadFile 函数,然后它将成功隐藏 div 标签部分。
但我必须先隐藏 div 标签部分,然后下载特定文件。请参考我的图片...
请指导我摆脱这个问题......