Upload file to an IIS server with AJAX using HTML and JavaScript

Tags: , , , ,



I want to be able to upload an image file (.png, .jpg, etc..) to my web-server (running IIS Server with ASPX) using nothing but HTML and AJAX.

Here’s the code:

<form id="personal-details-form" name="detailsfrm" method="POST" action="/ASPX/verifyPersonalDetails" enctype="multipart/form-data" novalidate>
  <label for="profile-pic-input">
    <img id="profile-pic" name="profilepic" class="profile-pic" src="/Media/user.png" onerror="document.profilepic.src = '/Media/user.png'" />
  </label>
  <img id="profile-pic-check" onerror="clearImage();" style="display: none;"/>
  <input id="profile-pic-input" name="pfpinput" type="file" accept="image/png, image/jpeg"
         onchange="readImage(this);" style="display: none" />

<!-- more code that has nothing to do with this question...-->
// JS
function readImage(input) {
    document.getElementById("personal-details-error").innerHTML = "";
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#profile-pic').attr('src', e.target.result);
            $('#profile-pic-check').attr('src', e.target.result);
        };

        reader.readAsDataURL(input.files[0]);
    }
}

function clearImage() {
    document.getElementById("personal-details-error").innerHTML = "Invalid image.";
    document.getElementById("profile-pic-input").value = "";
}

$("#personal-details-form").submit(function (e) {
    e.preventDefault();
    $(".form-field").addClass("used");
    document.getElementById("personal-details-error").innerHTML = ""; // Remove errors
    if (document.getElementById("personal-details-form").checkValidity()) {
        $.ajax({
            type: "POST",
            url: "../ASPX/verifyChangeDetails.aspx",
            data: $("#personal-details-form").serialize(),
            success: function (data) {

            },
        });
    }
});
if (Request.Files["pfpinput"] != null) {
    HttpPostedFile MyFile = Request.Files["pfpinput"];
    Response.Write(MyFile);
} else {
    Response.Write("Nope!");
}

I’ve heard that enctype=”multipart/form-data” works, but clearly doesn’t in my case…

What should I do in order for my AJAX code to upload the image file?

Answer

Turns out I needed a FormData object, and add a file onto it, along with other things, since I was using AJAX.

var formData = new FormData(document.detailsfrm);
formData.append("pfpinput", document.detailsfrm.pfpinput.files[0]);


Source: stackoverflow