1

I need to upload and save an image onto the server. I am using an XMLHttpRequest POST to send the image to the server and calling a class named imageSave.aspx. I am finding difficulty in "catching" the image from server side (imageSave.aspx) and saving it onto the server. Does anyone please have some tips as to how this is done or maybe link to a good article or something?

Code used to perform the http POST....

    xhr = new XMLHttpRequest();

                // Update progress bar etc
                xhr.upload.addEventListener("progress", function(evt) {
    if (evt.lengthComputable) {
    progressBar.style.width = (evt.loaded / evt.total) * 100 + "%";
    }
    else {
    // No data to calculate on
    }
    }, false);

    // File uploaded
    xhr.addEventListener("load", function() {
    progressBarContainer.className += " uploaded";
    progressBar.innerHTML = "Uploaded!";
    }, false);

    xhr.open("post", "imageSave.aspx", true);

    // Set appropriate headers
               xhr.setRequestHeader("Content-Type", "multipart/form-data");
       xhr.setRequestHeader("X-File-Name", file.fileName);
       xhr.setRequestHeader("X-File-Size", file.fileSize);
       xhr.setRequestHeader("X-File-Type", file.type);

       // Send the file
       xhr.send(file);

Much appreciated, JP

JeanPaul Galea
  • 113
  • 3
  • 11

1 Answers1

0

Read this other answer:

It'll get you an idea of why you can't upload an image using XMLHttpRequest.

UPDATE: Check this control of AJAX Control Toolkit - it'd be what you want! - :

Community
  • 1
  • 1
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • I see. So how are images usually uploaded after being selected by a client using an html INPUT element? – JeanPaul Galea Feb 07 '11 at 14:26
  • Doing a full post-back. Some have an hidden iframe which uploads the file and notifies the host page that an upload has been successfully done. Doing this approach, you get some kind of "AJAX-like" feel. Others use a 1px and hidden Flash to achieve the same goal. Non of these are good approaches, but since there's no standard solution for an asynchronous upload... – Matías Fidemraizer Feb 07 '11 at 14:27
  • using an iframe you would submit a form to the server right? so how do you save the image from server side then? – JeanPaul Galea Feb 07 '11 at 15:18
  • That form would have a form itself with application/octet-stream mime type and a file input too, which value will be assigned prior to post the form. Finally, the form is sent with file data and you can handle that as regular file uploads in ASP.NET. – Matías Fidemraizer Feb 07 '11 at 15:21
  • thanks Matias. sorry for taking up your time...but would you know of a good article I can read about how to do this? Thanks – JeanPaul Galea Feb 07 '11 at 15:25