要求
我正在尝试在用户选择文件后立即上传文件。我必须满足以下要求:
- 按钮的外观应与应用程序中的其他按钮相同。
- 用户选择文件后立即上传文件。
- 我需要它在UpdatePanel中,因为我必须对页面进行条件更新。我可以在文件选择(即
onchange
事件)上执行完整的postback。
当前代码
以下是我的视图文件的样子:
<asp:UpdatePanel ID="upData" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<div style="width: auto; float: right;">
<asp:Button ID="btnFileImportSkin" CssClass="ButtonSkin AddButton" Text="Import" Style="position: absolute; z-index: 2;" runat="server" OnClientClick="Javascript:onImport(); return false;" />
<asp:FileUpload ID="fileImport" Visible="false" Style="position:relative; opacity:0;" runat="server" onchange="Javascript:onFileSelected();" />
<%-- onchange="Javascript:this.form.submit();" /> --%>
<%-- <asp:Button ID="btnUpload" runat="server" OnClientClick="Javascript:alert('Uploading...'); __doPostBack('<%= btnUpload.ID %>', ''); return false;" /> --%>
<asp:Button ID="btnUpload" OnClick="btnUpload_Click" runat="server" />
</div>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload" />
</Triggers>
</asp:UpdatePanel>
相关的Javascript代码:
<script type="text/javascript">
function onImport() {
var fileImportClientId = '<%= fileImport.ClientID %>';
document.getElementById(fileImportClientId).click();
}
function onFileSelected() {
alert("File Selected");
// I have tried calling the function directly and with a timeout
setTimeout(onUpload, 20);
}
function onUpload() {
var btnUploadClientId = '<%= btnUpload.ClientID %>';
document.getElementById(btnUploadClientId).click();
}
</script>
后台代码:
protected void btnUpload_Click(object sender, EventArgs e)
{
// PostedFile is null first time code gets here on user selecting a file
if (fileImport.PostedFile != null)
{
if (fileImport.PostedFile.FileName.Length > 0)
{
ImportFromFile();
}
}
}
Explanation/Flow
- User clicks on
btnFileImportSkin
button. - The function
onImport
is called, which programmatically clicks on thefileimport
button. - User selects a file, and presses Open.
onFileSelected
is called.onUpload
is called successfully.btnUpload_Click
is called successfully every time.
However the Problem is that
fileImport.PostedFile is null the first time user selects a file. Everything works fine the second time and from there on.
Related
This question is closely related to my problem, but the OP probably wanted an Async upload solution as in Gmail. I have already tried doing the following as in the answers to this question:
- __doPostBack() in OnClientClick event of
btnUpload
- this.form.submit() onchange event of my
FileUpload
control. - Setting the onchange attribute of
FileUpload
control in Page_PreRender
Additional Notes
- This thing worked perfectly when I did not have update panels. I was doing this.form.submit() directly in onchange event of
FileUpload
control. - Target framework is .NET 4.0
NOTE: Added a Visible="false" in FileUpload
control above. It was the problem but I had ignored it while asking question.