Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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:

VB.NET
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:

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:

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
Posted
Updated 20-Dec-16 4:27am
Comments
F-ES Sitecore 20-Dec-16 8:23am    
You can't upload files like that via javascript as it has no access to the file system. Google "asp.net asynch file upload" and you'll find various options for how to do this.
H.AL 20-Dec-16 8:36am    
can you give me some links?

1 solution

If you're using a modern browser[^], you can use the FormData class[^] to upload the file:
JavaScript
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900