How to solve second button click download problem on SharePoint 2010

来源:互联网 发布:琅琊榜飞剑升阶数据 编辑:程序博客网 时间:2024/06/03 17:07

/*

Author: Jiangong SUN

*/


In fact, I have a button and it will generate a file and propose users to download it when users click on it. But it works only for the first time.

<asp:Button runat="server" ID="Btn" OnClick="Btn_Click" Text="Generate" />

The principle of the file generation is it collect relevant information and put them into memory stream, and push them to browsers. When it's about to push the memory, it will generate a file name and then add it for the memory stream. 


MemoryStream ms = GetStream();byte[] byteArray = ms.ToArray();string fileName = "test.doc";Response.Clear();Response.AddHeader("Content-Disposition", fileName);Response.AddHeader("Content-Length", byteArray.Length.ToString());// Set the HTTP MIME type of the output streamResponse.ContentType = "APPLICATION/OCTET-STREAM";//Write the data in the responseResponse.BinaryWrite(byteArray);Response.Flush();Response.End();


Once the file is downloaded, I need to be able to refresh this page. Originally, I want to redirect this page to itself with some code like:

Response.Redirect(Request.RawUrl);

or

Response.Redirect(Request.RawUrl, true);

or 

Response.Buffer = true;

And delete Response.Flush();


But it didn't work for me. I've searched a lot on internet and can't find answer in this direction.


The source of problem is that when I click the button, the form will be submitted. And once the form is submitted, I can't submit anything without refreshing this page. To resolve this problem, you have to do something to tell your browser the form is not yet submitted.

To do so, you have a variable in SharePoint, set variable "_spFormOnSubmitCalled" to false. Every time the user click on the button, this variable will be set to true, at the same time I force it to be false. And in this way, I can click on button at anytime, and it works.

<asp:Button runat="server" ID="Btn" OnClick="Btn_Click" OnClientClick="window.setTimeout(function() { _spFormOnSubmitCalled = false; }, 10);" Text="Generate" />


I've spent one whole day to solve this problem and I'm a newbie to SharePoint. I hope this post can do help in your daily SP development. Enjoy coding!


Reference: http://stackoverflow.com/questions/7749393/no-more-post-back-after-file-download-in-sharepoint