Solved

Access Asp:FileUpload from Javascript/Jquery

Posted on 2014-09-26
3
1,033 Views
Last Modified: 2014-10-03
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
Comment
Question by:adworldmedia
  • 2
3 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 40348159
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
 

Accepted Solution

by:
adworldmedia earned 0 total points
ID: 40348698
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
 

Author Closing Comment

by:adworldmedia
ID: 40358984
The other solution didn't help, and I figured out how to do it on my own.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that undeā€¦
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now