Solved

Access Asp:FileUpload from Javascript/Jquery

Posted on 2014-09-26
3
1,159 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

What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

Question has a verified solution.

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

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
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)

688 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