Solved

Access Asp:FileUpload from Javascript/Jquery

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

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
WPF Select Items 3 25
global Variable - 2 functions in powershell 1 21
Table style position to the left 8 25
javascript and jquery question 4 24
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…

749 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