我在ASP.net中使用FileUpload控件。格式化输入按钮是一件很痛苦的事情,我试图通过使用一个简单的(格式化)按钮激活一个点击FileUpload控件的jQuery函数来解决这个问题。这是我的格式化按钮,名为btn_upload_FILE:
<asp:Button ID="btn_upload_FILE" runat="server" class="c_button" Text="Import an EDD" OnClick="Main" />
这是FileUpload控件:
<asp:FileUpload runat="server" ID="FILE_uploader"></asp:FileUpload>
这是jQuery:
$('#<%= btn_upload_FILE.ClientID %>').click(function () {
$('#<%= FILE_uploader.ClientID %>').click();
});
超级简单,效果很好,打开文件浏览器,让我选择一个文件。
问题是,即使FileUpload控件似乎正常工作,我选择的文件实际上并未加载到FileUpload控件中,因此我的代码隐藏无法看到它。它看起来像它正在工作,但FileUpload最终为空。 FileUpload的.change事件没有被触发,所以我什么都不知道。如果我只按FileUpload控件的按钮,它就可以正常工作。
有人可以告诉我为什么FileUpload没有收到文件,即使我可以浏览它吗?任何帮助一如既往地受到赞赏。
答案 0 :(得分:3)
要使用FileUpload上传文件,您需要进行完整的回发,因此您必须使用一个按钮:
<asp:Button ID="btn_upload_FILE" runat="server" class="c_button" Text="Import an EDD" OnClick="Main" />
<asp:FileUpload runat="server" ID="FILE_uploader"></asp:FileUpload>
在后面的代码中,按钮的Main方法:
protected void Main(object sender, EventArgs e)
{
// Specify the path on the server to
// save the uploaded file to.
String savePath = @"c:\temp\uploads\";
// Before attempting to perform operations
// on the file, verify that the FileUpload
// control contains a file.
if (FILE_uploader.HasFile)
{
// Get the name of the file to upload.
String fileName = FILE_uploader.FileName;
// Append the name of the file to upload to the path.
savePath += fileName;
// Call the SaveAs method to save the
// uploaded file to the specified path.
// This example does not perform all
// the necessary error checking.
// If a file with the same name
// already exists in the specified path,
// the uploaded file overwrites it.
FileUpload1.SaveAs(savePath);
// Notify the user of the name of the file
// was saved under.
UploadStatusLabel.Text = "Your file was saved as " + fileName;
}
else
{
// Notify the user that a file was not uploaded.
UploadStatusLabel.Text = "You did not specify a file to upload.";
}
}
您可以在MSDN找到更多信息。
希望它有所帮助!
修改强>
您也可以使用jquery。首先,通过将其display属性设置为none来隐藏asp:按钮:
<asp:Button ID="btn_upload_FILE" runat="server" class="c_button" Text="Import an EDD" OnClick="Main" Style="display:none" />
现在添加jquery以在FileUpload中有文件时触发此按钮的click事件:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('change', '#<%= FILE_uploader.ClientID %>', function () {
if (document.getElementById('<%= FILE_uploader.ClientID %>').files.length === 0) {
return;
}
$('#<%= btn_upload_FILE.ClientID %>').trigger('click');
});
});
</script>
不要忘记在页面的顶部添加对jquery的引用。
答案 1 :(得分:0)
您的表单的Enctype是否设置为“multipart / form-data”?
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Form.Enctype = "multipart/form-data";
}