?
Solved

Access Asp:FileUpload from Javascript/Jquery

Posted on 2014-09-26
3
Medium Priority
?
1,218 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

WordPress Tutorial 2: Terminology

An important part of learning any new piece of software is understanding the terminology it uses. Thankfully WordPress uses fairly simple names for everything that make it easy to start using the software.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
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)
Suggested Courses

801 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