• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1331
  • Last Modified:

Access Asp:FileUpload from Javascript/Jquery

I'm currently using a bootstrap Wizard (https://github.com/amoffat/bootstrap-application-wizard) and I have an Asp:FileUpload control within it.

I need to use JQuery to parse the form data and pass it to a C# static WebMethod..  I've retrieved all the control values fine, but I am having trouble getting the File Upload data.

How can I pass the uploaded file's information to the WebMethod via Jquery or Javascript?
0
adworldmedia
Asked:
adworldmedia
  • 2
1 Solution
 
leakim971PluritechnicianCommented:
You cannot use JSON to send files

If you are OK to go away JSON, you may use FormData to POST your data included your files.
Check here the example :  https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
0
 
adworldmediaCTOAuthor Commented:
I was able to solve the solution in sort of a round-about way...

I used Javascript/jQuery to grab the file information, pass it to a C# handler that saves the file on the web server and passes the full path and filename back to the system... then I pass the data to a C# function via the Javascript PageMethod... and grab the information that way.  Sounds round-about; but it works!

The HTML
<div class="wizard-input-section">
      <p style="font-weight:bolder;">Upload Banner Image (JPG or GIF)</p>
              <div class="control-group">
                      <asp:FileUpload ID="fileBanner" runat="server" /><br />                            
               </div>
</div>

Open in new window


The Javascript/JQuery:

wizard.on("submit", function (wizard) {
        //Check if file is to be uploaded
        var xhr = new XMLHttpRequest;
        var imgVal = $("#fileBanner").val();
        if (imgVal != '') {
            //Filename found
            var data = new FormData();
            var files = $("#fileBanner").prop('files');
            for (var i = 0; i < files.length; i++) {
                data.append(files[i].name, files[i]);
            }
            xhr.onreadystatechange = UploadReady;
            xhr.open("POST", "UploadHandler.ashx");
            xhr.send(data);
        }
        function UploadReady() {
            if (xhr.readyState == 4) {
                bannerFile = xhr.responseText;
                PageMethods.createCampaignAd( bannerFile, createSuccess, createError);
            }
        }
        function createSuccess(result)
        {
            $("#wizardsuccess").text(result);
            wizard.submitSuccess();
            wizard.hideButtons();
            wizard.updateProgressBar(0);
        }
        function createError(result)
        {
            $("#wizardfailure").text(result);
            wizard.submitFailure();
            wizard.hideButtons();
        }

Open in new window


Then I created an upload handler code that saves the uploaded image on a folder on the web server, and passes the file path and name back...

<%@ WebHandler Language="C#" Class="UploadHandler" %>

using System;
using System.Web;
using System.IO;
using System.Collections;

public class UploadHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        HttpFileCollection files = context.Request.Files;
        ArrayList response = new ArrayList();
        string uploadedFiles;
        foreach (string key in files)
        {
            HttpPostedFile file = files[key];
            string filename = file.FileName;
            string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            string name = Path.GetFileNameWithoutExtension(filename);
            string ext = Path.GetExtension(filename);
            filename = name + "_" + timestamp + ext;
            filename = context.Server.MapPath("~/uploads/" + filename);
            file.SaveAs(filename);
            response.Add(filename);
        }
        uploadedFiles = string.Join(",", response.ToArray());
        context.Response.ContentType = "text/plain";
        context.Response.Write(uploadedFiles);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

Open in new window


Then the code to retrieve the file data from the path and filename:

            if(bannerFile != "")
            {
                if(File.Exists(bannerFile))
                {
                    FileStream fs = new FileStream(bannerFile, FileMode.Open, FileAccess.Read);
                    BinaryReader br = new BinaryReader(fs);
                    byte[] btArr = br.ReadBytes((int)fs.Length);
                    br.Close();
                    fs.Close();
                    _bannerCreative.backupFileName = Path.GetFileName(bannerFile);
                    _bannerCreative.backupFileBody = Convert.ToBase64String(btArr);
                }
            }   

Open in new window

0
 
adworldmediaCTOAuthor Commented:
The other solution didn't help, and I figured out how to do it on my own.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now