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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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]);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0