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:
JavaScript
x
10
10
1
<form id="personal-details-form" name="detailsfrm" method="POST" action="/ASPX/verifyPersonalDetails" enctype="multipart/form-data" novalidate>
2
<label for="profile-pic-input">
3
<img id="profile-pic" name="profilepic" class="profile-pic" src="/Media/user.png" onerror="document.profilepic.src = '/Media/user.png'" />
4
</label>
5
<img id="profile-pic-check" onerror="clearImage();" style="display: none;"/>
6
<input id="profile-pic-input" name="pfpinput" type="file" accept="image/png, image/jpeg"
7
onchange="readImage(this);" style="display: none" />
8
9
<!-- more code that has nothing to do with this question-->
10
JavaScript
1
35
35
1
// JS
2
function readImage(input) {
3
document.getElementById("personal-details-error").innerHTML = "";
4
if (input.files && input.files[0]) {
5
var reader = new FileReader();
6
reader.onload = function (e) {
7
$('#profile-pic').attr('src', e.target.result);
8
$('#profile-pic-check').attr('src', e.target.result);
9
};
10
11
reader.readAsDataURL(input.files[0]);
12
}
13
}
14
15
function clearImage() {
16
document.getElementById("personal-details-error").innerHTML = "Invalid image.";
17
document.getElementById("profile-pic-input").value = "";
18
}
19
20
$("#personal-details-form").submit(function (e) {
21
e.preventDefault();
22
$(".form-field").addClass("used");
23
document.getElementById("personal-details-error").innerHTML = ""; // Remove errors
24
if (document.getElementById("personal-details-form").checkValidity()) {
25
$.ajax({
26
type: "POST",
27
url: "../ASPX/verifyChangeDetails.aspx",
28
data: $("#personal-details-form").serialize(),
29
success: function (data) {
30
31
},
32
});
33
}
34
});
35
JavaScript
1
7
1
if (Request.Files["pfpinput"] != null) {
2
HttpPostedFile MyFile = Request.Files["pfpinput"];
3
Response.Write(MyFile);
4
} else {
5
Response.Write("Nope!");
6
}
7
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?
Advertisement
Answer
Turns out I needed a FormData object, and add a file onto it, along with other things, since I was using AJAX.
JavaScript
1
3
1
var formData = new FormData(document.detailsfrm);
2
formData.append("pfpinput", document.detailsfrm.pfpinput.files[0]);
3