从javascript传递给webmethod的Fileupload.hasfile返回false [英] Fileupload.hasfile passed from javascript to webmethod is returning false

查看:53
本文介绍了从javascript传递给webmethod的Fileupload.hasfile返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了避免回发和加载页面,我想到了一种JavaScript方法,它接受所选文件并将其上传到服务器上。但是每当我的方法检查HasFile是真还是假时,答案总是假的。当然,因为我没有在Asp:UpdatePannel中实现我的控件,并且没有任何触发器在单击上传按钮时回发我的代码。所以现在我的问题是:无论如何将填充的文件传递给我的webMethod?以下是我的网络方法:



 公共 功能 UploadImages( ByVal  fileUpload  As  FileUpload) As  UploadedImage 

Dim uploadedImage As UploadedImage

Dim 路径作为 字符串 = Server.MapPath( 〜/ UploadedImages /
Dim fileOK As 布尔 = 错误
尝试
如果 fileUpload.HasFile 然后
Dim fileExtension As 字符串
fileExtension = System.IO.Path。 _
GetExtension(fileUpload.FileName).ToLower()
Dim allowedExtensions As 字符串()= _
{ 。 jpg .jpeg 。png 。gif }
对于 i 作为 整数 = 0 allowedExtensions.Length - 1
如果 fileExtension = allowedExtensions(i)那么
fileOK = True
结束 如果
下一步
如果 fileOK 那么
尝试
fileUpload.PostedFile.SaveAs(路径& _
fileUpload.FileName)
uploadedImage.Success = 上传文件!
Catch ex As 例外
uploadedImage.Success = 无法上传文件。
结束 < span class =code-keyword>尝试
其他
uploadedImage.Success = 无法接受此类型的文件。
结束 如果
uploadedImage.UploadedURL = fileUpload.FileName
其他
uploadedImage.UploadedURL =
uploadedImage.Success = 没有要上传的文件。
结束 如果
Catch ex As 例外
uploadedImage.UploadedURL = < span class =code-string>
uploadedImage.Success = 无法上传文件
结束 尝试

返回 uploadedImage

结束 功能





以下是我在Javascript中的功能:



  function  ChooseFileFunction(){

var fileToUpload = document .getElementById(' <%= FileUpload1.ClientID%>');

$ .ajax({
type:' POST'
url:' MyWebService.asmx / UploadImages'
data:< span class =code-sdkkeyword> JSON .stringify({fileUpload:fileToUpload}),
contentType: application / json; charset = utf-8
dataType: json
成功: function (响应){alert( success);}
});

}





在asp.net中:



 <   div     class   =  ChooseFile_Div >  <   asp:FileUpload     ID   =  FileUpload1    CssClass   =  ChooseFile_FileUpload    runat   =  server   <温泉n class =code-keyword> /  >  <   / div  >  
< br / >
< asp:按钮 ID = Button1 OnClientClick = ChooseFileFunction(); return false; runat = 服务器 文本 = 上传 / >





我是什么尝试过:



我已经尝试了asp:AsyncPostBackTrigger,后面有一个方法,但返回的文件值为false

解决方案

.ajax({
type:' POST'
url:' MyWebService.asmx / UploadImages'
data : JSON .stringify({fileUpload:fileToUpload}),
contentType: 应用/ JSON; charset = utf-8
dataType: json
成功: function (响应){alert( 成功);}
});

}





In asp.net:



 <   div     class   =   ChooseFile_Div >  <   asp:FileUpload     ID   =  FileUpload1    CssClass   =  ChooseFile_FileUpload    runat   =  server    /  >  <   / div  >  
< br / >
< asp:按钮 ID = Button1 OnClientClick = ChooseFileFunction(); return false; runat < span class =code-keyword> = server 文本 = 上传 / >





我尝试了什么:



我用代码中的方法尝试了asp:AsyncPostBackTrigger后面,但返回的文件值为false


如果您正在使用现代浏览器 [ ^ ],您可以使用 FormData [ ^ ]上传文件:

< pre lang =Javascript> function ChooseFileFunction(){

var fileToUpload = document .getElementById(' <%= FileUpload1。 ClientID%>');


.ajax({
type:' POST'
url:' MyWebService.asmx / UploadImages '
数据: new FormData(fileToUpload.form)
})。done( function (){
alert( success);
})。失败( function (){
alert( failed);
});
}



如果您需要支持旧浏览器,那么您需要使用隐藏的< iframe> ,并将表单的目标更改为指向该帧。或者,您可以使用许多可用的jQuery文件上传插件之一。



在服务器端,您需要从<$ c中删除参数$ c> UploadImages 方法,并从 HttpContext.Current.Request.Files 中读取文件。


In order to avoid post back and loading pages, I have thought of a JavaScript method that takes the chosen file and upload it on the server. But whenever my method is checking if HasFile is true or false, the answer is always false. Of course because I am not implementing my controls in an Asp:UpdatePannel and there aren't any triggers to postback my code when upload button is clicked. So now my question is: Is there anyway to pass a filled file to my webMethod? Below is my webmethod:

Public Function UploadImages(ByVal fileUpload As FileUpload) As UploadedImage

    Dim uploadedImage As New UploadedImage

    Dim path As String = Server.MapPath("~/UploadedImages/")
    Dim fileOK As Boolean = False
    Try
        If fileUpload.HasFile Then
            Dim fileExtension As String
            fileExtension = System.IO.Path. _
                GetExtension(fileUpload.FileName).ToLower()
            Dim allowedExtensions As String() = _
                {".jpg", ".jpeg", ".png", ".gif"}
            For i As Integer = 0 To allowedExtensions.Length - 1
                If fileExtension = allowedExtensions(i) Then
                    fileOK = True
                End If
            Next
            If fileOK Then
                Try
                    fileUpload.PostedFile.SaveAs(path & _
                         fileUpload.FileName)
                    uploadedImage.Success = "File uploaded!"
                Catch ex As Exception
                    uploadedImage.Success = "File could not be uploaded."
                End Try
            Else
                uploadedImage.Success = "Cannot accept files of this type."
            End If
            uploadedImage.UploadedURL = fileUpload.FileName
        Else
            uploadedImage.UploadedURL = ""
            uploadedImage.Success = "No File to upload."
        End If
    Catch ex As Exception
        uploadedImage.UploadedURL = ""
        uploadedImage.Success = "Could not upload file"
    End Try

    Return uploadedImage

End Function



Below is my function in Javascript:

function ChooseFileFunction() {

        var fileToUpload = document.getElementById('<%= FileUpload1.ClientID %>');

        $.ajax({
            type: 'POST',
            url: 'MyWebService.asmx/UploadImages',
            data: JSON.stringify({ fileUpload : fileToUpload }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) { alert("success"); }
        });

    } 



In asp.net:

<div class="ChooseFile_Div"><asp:FileUpload ID="FileUpload1" CssClass="ChooseFile_FileUpload" runat="server" /></div>
<br/>
<asp:Button ID="Button1" OnClientClick="ChooseFileFunction();return false;" runat="server" Text="Upload" />



What I have tried:

I have tried the asp:AsyncPostBackTrigger with a method in code behind, but the returned file value was false

解决方案

.ajax({ type: 'POST', url: 'MyWebService.asmx/UploadImages', data: JSON.stringify({ fileUpload : fileToUpload }), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { alert("success"); } }); }



In asp.net:

<div class="ChooseFile_Div"><asp:FileUpload ID="FileUpload1" CssClass="ChooseFile_FileUpload" runat="server" /></div>
<br/>
<asp:Button ID="Button1" OnClientClick="ChooseFileFunction();return false;" runat="server" Text="Upload" />



What I have tried:

I have tried the asp:AsyncPostBackTrigger with a method in code behind, but the returned file value was false


If you're using a modern browser[^], you can use the FormData class[^] to upload the file:

function ChooseFileFunction() {
    
    var fileToUpload = document.getElementById('<%= FileUpload1.ClientID %>');


.ajax({ type: 'POST', url: 'MyWebService.asmx/UploadImages', data: new FormData(fileToUpload.form) }).done(function(){ alert("success"); }).fail(function(){ alert("failed"); }); }


If you need to support older browsers, then you'll need to use a hidden <iframe>, and change your form's target to point to that frame. Alternatively, you could use one of the many available jQuery file upload plugins.

On the server-side, you'll need to remove the parameter from your UploadImages method, and read the file from HttpContext.Current.Request.Files instead.


这篇关于从javascript传递给webmethod的Fileupload.hasfile返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆