javascript 单击提交按钮时重置文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18755355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:06:16  来源:igfitidea点击:

File upload is reset on submit button click

javascriptasp.netformsinternet-explorerfile-upload

提问by IT researcher

I am using upload feature in my asp website. So i am using file input type. But this control add a default upload button browse and a textbox where path is shown after selecting file in Internet explorer. I don't want to show browse button etc. So what i did is add a button "Attach a File" and i have written script 'triggerFileUpload' function where i make it to click on upload control. So now when i click on "Attach a File" button browse for file windows appears and can select file to upload. But when i click on submit button the file upload control becomes reset and file is not uploaded. Error is that on clicking to submit button the file control becomes null. It happens only in internet explorer. So please help me to solve this.Below is code which can show the problem i am facing in IE.Same problem comes if i use asp:FileUpload control also. (my plan is to hide the file control and show only attach file button to user).

我在我的 asp 网站中使用上传功能。所以我使用文件输入类型。但是这个控件添加了一个默认的上传按钮浏览和一个在 Internet Explorer 中选择文件后显示路径的文本框。我不想显示浏览按钮等。所以我所做的是添加一个按钮“附加文件”,并且我编写了脚本“triggerFileUpload”函数,我让它点击上传控件。所以现在当我点击“附加文件”按钮时,会出现浏览文件窗口并可以选择要上传的文件。但是当我点击提交按钮时,文件上传控件被重置并且文件没有上传。错误是单击提交按钮时文件控件变为空。它只发生在 Internet Explorer 中。所以请帮我解决这个问题。下面是可以显示我在 IE 中面临的问题的代码。如果我也使用 asp:FileUpload 控件,也会出现同样的问题。(我的计划是隐藏文件控件并仅向用户显示附加文件按钮)。

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
      function triggerFileUpload() {
          document.getElementById("FileUploaddd2").click();
      }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input id="Button2" type="button" onclick="triggerFileUpload()" value="Attach a File" />
     <input type="file" id="FileUploaddd2" runat="Server" />
     <br />
    <asp:Button ID="btnSubmit" runat="server" BorderColor="Black" 
                            BorderStyle="Solid" BorderWidth="1px"
                            Text="Submit" />
    </div>
    </form>
</body>
</html>

Download the sample code here

此处下载示例代码

UPDATE

更新

To reproduce the error i am facing

重现我面临的错误

1) run the project i have given in the download link

1)运行我在下载链接中给出的项目

2) Test in Internet explorer-any version

2)在Internet Explorer-任何版本中测试

3)Click on attach a file button (not on browse,it is intended to make visible false,here shown only for example purpose)

3)点击附加文件按钮(不是浏览,目的是使可见假,这里显示仅用于示例目的)

4)browse for files in windows appearing and click OK

4)在出现的窗口中浏览文件,然后单击确定

5)now click on Save button.

5)现在点击保存按钮。

When save button is clicked btnsave_Click function should trigger,but it is not triggering.If i click again on save button btnsave_Click gets triggered.But this time the upload control will not be having the file selected.you can see it in the textbox provided by browse control also(only for showing this i made browse control as visible)

当点击保存按钮时 btnsave_Click 函数应该触发,但它不会触发。如果我​​再次点击保存按钮 btnsave_Click 被触发。但是这次上传控件不会选择文件。你可以在提供的文本框中看到它也浏览控件(仅用于显示此我将浏览控件设为可见)

So now question why btnsave_Click is not triggered for the first time?

那么现在问为什么第一次没有触发 btnsave_Click ?

采纳答案by afzalulh

Problem is IE wouldn't let you submit a file through javascript, user have to click the file input. It is a known problem, described here:

问题是 IE 不允许您通过 javascript 提交文件,用户必须单击文件输入。这是一个已知问题,描述如下:

When an file-input is opened via a scripted, forced click() event, IE won't let you submit the form. If you click the file-input via your own mouse (what we don't want), IE will let you submit the form.Open file input dialog and upload onchange possible in IE?

When an file-input is opened via a scripted, forced click() event, IE won't let you submit the form. If you click the file-input via your own mouse (what we don't want), IE will let you submit the form.在 IE 中打开文件输入对话框并上传 onchange 可能吗?

and also here: File Upload Using Javascript returns 'Access Denied' Error With Stylized to a button

还有这里: 使用 Javascript 的文件上传返回“访问被拒绝”错误,样式化为按钮

So, you have to trick the user, make the file-input transparent and place your button under the file-input. When user will click your button, they will click the file input instead.

因此,您必须欺骗用户,使文件输入透明并将您的按钮放在文件输入下。当用户单击您的按钮时,他们将改为单击文件输入。

With the css (probably you will need to tweak it) your markup should look like below:

使用 css(可能你需要调整它)你的标记应该如下所示:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <style type="text/css">
        .fileContainer {
            overflow: hidden;
            position: relative;
        }

        #FileUploaddd2 {
            position: relative;
            text-align: right;
            -moz-opacity: 0;
            filter: alpha(opacity: 0);
            opacity: 0;
            z-index: 2;
            left: -130px;
        }

        #Button2 {
            position: absolute;
            top: 0px;
            left: 0px;
            z-index: 1;
        }
    </style>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <label class="fileContainer">
                <input id="Button2" type="button" value="Attach a File" />
                <input type="file" id="FileUploaddd2" runat="Server" />
            </label>
            <br />
            <br />
            <asp:Button ID="btnSubmit" runat="server" BorderColor="Black"
                BorderStyle="Solid" BorderWidth="1px"
                Text="Submit" />
        </div>
    </form>
</body>
</html>

And in the code behind you can catch the submitted file

在后面的代码中,您可以捕获提交的文件

Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
    Dim file As System.Web.HttpPostedFile = FileUploaddd2.PostedFile
    If Not file Is Nothing Then
        'Save file?
    End If
End Sub

EDIT:If you want to show the filename in a label, you can do the following:

编辑:如果要在标签中显示文件名,可以执行以下操作:

In Input file's change event call a jsfunction:

在输入文件的更改事件中调用 jsfunction:

<input type="file" id="FileUploaddd2" runat="Server" onchange="setlabelvalue();" />

Add a label to display filename:

添加标签以显示文件名:

<asp:Label ID="lblFileName" runat ="server" Text=""></asp:Label>

Add the setlabelvalue() js function:

添加 setlabelvalue() js 函数:

function setlabelvalue() {
            var filename = document.getElementById("FileUploaddd2").value;
            var lastIndex = filename.lastIndexOf("\");

            if (lastIndex >= 0) {
                filename = filename.substring(lastIndex + 1);
            }
            document.getElementById('<%=lblFileName.ClientID%>').innerHTML = filename;
        }

回答by Prashant Lakhlani

File upload in asp.net is pretty straight forward but requires some tweaks. Here is the example:

asp.net 中的文件上传非常简单,但需要一些调整。这是示例:

<form id="Form1" method="post" runat="server" enctype="multipart/form-data">
<input id="filMyFile" type="file" runat="server"><br/>
<asp:Button ID="btnSubmit" runat="server" BorderColor="Black" 
                            BorderStyle="Solid" BorderWidth="1px"
                            Text="Submit" />
</form>

Try this and it should work.

试试这个,它应该可以工作。

Once you upload file, you have make filMyFile.Visible=false;and add label to show uploaded file and link button to remove it.

上传文件后,您可以制作filMyFile.Visible=false;并添加标签以显示上传的文件和链接按钮以将其删除。

I hope that makes sense now.

我希望现在说得通了。

Here is a really straight forward reference: http://www.codeproject.com/Articles/1757/File-Upload-with-ASP-NET

这是一个非常直接的参考:http: //www.codeproject.com/Articles/1757/File-Upload-with-ASP-NET

回答by Jean Carlos

i don't know if i misunderstood the question, but why don't you do:

我不知道我是否误解了这个问题,但你为什么不这样做:

triggerFileUpload() {
      document.forms[0].submit();
}

回答by Naveed Butt

Are you sure that the click is working ? Because I think you are not writing the java script code correctly.

你确定点击有效吗?因为我认为您没有正确编写java脚本代码。

You need to get the ClientIDof the file upload in java script

您需要ClientID在java脚本中获取文件上传的

like this:

像这样:

document.getElementById('<%=  FileUploaddd2.ClientID %>').click();

After your Update, I was able to run the code successfully...

更新后,我能够成功运行代码...

I think you need to add this line after the try catch block inside the if block in your server side code...

我认为您需要在服务器端代码的 if 块内的 try catch 块之后添加这一行...

    Try
        sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName)
        'saving the file
        FileUpload1.SaveAs("c:\SaveDirectory\" + FileUpload1.FileName)
        'Showing the file information
        sb.AppendFormat("<br/> Save As: {0}", FileUpload1.PostedFile.FileName)
        sb.AppendFormat("<br/> File type: {0}", FileUpload1.PostedFile.ContentType)
        sb.AppendFormat("<br/> File length: {0}", FileUpload1.PostedFile.ContentLength)
        sb.AppendFormat("<br/> File name: {0}", FileUpload1.PostedFile.FileName)
    Catch ex As Exception
        sb.Append("<br/> Error <br/>")
        sb.AppendFormat("Unable to save file <br/> {0}", ex.Message)
    End Try
    lblmessage.Text = sb.ToString()

AFTER UPDATE

更新后

After seeing the update regarding the Internet Explorer. I think your problem is this:

看到有关 Internet Explorer 的更新后。我认为你的问题是这样的:

Simulating the click on input type="file" using javascript

使用 javascript 模拟点击 input type="file"

This might also help: Browser check before executing an event

这也可能有帮助:执行事件之前的浏览器检查

You can also use Ajax Control Toolkit's AjaxFileUpload for better display and features like drag and drop are already implemented in that: Have a look. This way you won't have to simulate a click on the button.

您还可以使用 Ajax Control Toolkit 的 AjaxFileUpload 以获得更好的显示效果,并且已经在其中实现了诸如拖放之类的功能:看看. 这样您就不必模拟单击按钮。