简体   繁体   English

按钮的click事件触发asp.net中的fileupload控件

[英]click event of a button to fire fileupload control in asp.net

I have a file upload Control and I have made this invisible. 我有一个文件上传控件,并且使它不可见。

I want to enable a browse Button for that file upload control when I click another Button . 我想启用的浏览Button ,当我点击另一个有文件上传控制Button

How can I do it? 我该怎么做?

First make a file up loader like this one 首先像这样制作一个文件加载器

To upload a file you need to do 2 things 要上传文件,您需要做2件事

1) Select the file. 1)选择文件。 (click browse button) (单击浏览按钮)

2) Send it to server. 2)将其发送到服务器。 (click the upload button) (点击上传按钮)

So first lets write a java-script to do these.` 因此,首先让我们编写一个Java脚本来完成这些操作。

<script type="text/javascript" > 
function uploadImage() {
    $('#MainContent_UploadButton').click()
}
function selectFile() {
    $('#MainContent_FileUploadControl').click();
}
</script>

Now make the file upload controller upload itself as soon as a file is selected 现在,使文件上传控制器在选择文件后立即自行上传

 <asp:FileUpload id="MainContent_FileUploadControl" runat="server" 
            onChange="uploadImage()" class="hidden"/>

Then make a new button and let it select the file as soon as it is clicked. 然后创建一个新按钮,让它在单击文件后立即选择文件。

    <asp:Button ID="MainContent_UploadButton" runat="server" Text="Upload File" 
            OnClientClick="selectFile(); return false;" />

The most important point is put "return false" in the onClientClick field. 最重要的一点是在onClientClick字段中输入“ return false”。 It will block the buttons post back and let you choose a file without refreshing the page. 它将阻止按钮回发,并让您选择文件而无需刷新页面。

Now hide the unwanted components using css and you are done !! 现在,使用CSS隐藏不需要的组件,您就完成了!

<asp:FileUpload ID="FileUpload1" runat="server" style="display:none;"/>
<input id="btnFileUpload" type="button" value="Add" runat="server" />

btnFileUpload.Attributes.Add("onclick", "document.getElementById('" + FileUpload1.ClientID + "').click();");

I think this is not possible. 我认为这是不可能的。 This would likely be a security issue if a script could upload (or at least trigger the upload process) invisible from any user interaction. 如果脚本可以上载(或至少触发上载过程)对任何用户交互都不可见,则这可能是一个安全问题。


Update: 更新:

Seems that someone actually developed a solution to hide the upload control . 似乎有人实际上开发了隐藏上传控件的解决方案 From what I read it seems to take some effort to develop and uses JavaScript. 从我阅读的内容来看,似乎需要花费一些精力来开发和使用JavaScript。

Personally, I wouldn't dare to guarantee that this works on all platforms (just imagine someone with a BlackBerry or Windows Phone visits your website...) and thus avoid it. 就我个人而言,我不敢保证在所有平台上都可以正常工作(想象一下拥有BlackBerry或Windows Phone的人访问了您的网站...)从而避免了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM