ASP.net FileUploader控件 – 单击使用jQuery

我在ASP.net中使用FileUpload控件。 格式化输入按钮是一件很痛苦的事情,我试图通过使用一个简单的(格式化)按钮激活一个单击FileUpload控件的jQuery函数来解决这个问题。 这是我的格式化按钮,名为btn_upload_FILE:

 

这是FileUpload控件:

  

这是jQuery:

 $('#').click(function () { $('#').click(); }); 

超级简单,它工作得很好,它打开文件浏览器,让我选择一个文件。

问题是,即使FileUpload控件似乎正常工作,我选择的文件实际上并未加载到FileUpload控件中,因此我的代码隐藏无法看到它。 看起来它正在工作,但FileUpload最终为空。 FileUpload的.change事件没有被触发,所以我什么都不知道。 如果我只按FileUpload控件的按钮,它工作正常。

任何人都可以告诉我为什么FileUpload没有收到文件,即使我可以浏览它? 任何帮助一如既往地受到赞赏。

要使用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:按钮:

  

现在添加jquery以在FileUpload中有文件时触发此按钮的click事件:

   

并且不要忘记在页面的顶部添加对jquery的引用。

您的Form的Enctype是否设置为“multipart / form-data”?

 protected void Page_Load(object sender, EventArgs e) { this.Page.Form.Enctype = "multipart/form-data"; }