要使用 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:button:
<asp:Button ID="btn_upload_FILE" runat="server" class="c_button" Text="Import an EDD" OnClick="Main" Style="display:none" />
现在添加 jquery 以在 FileUpload 中有文件时触发此按钮的单击事件:
<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 的引用。