I have been developing a file sharing service, but I encountered a problem. Despite selecting a file, AJAX is not recognizing this selection and the file is not automatically being uploaded. Consequently, the response is not being processed or inserted into a particular DIV on the page.
HTML + FORM
<div class="file-input-wrapper">
<form method="post" enctype="multipart/form-data" action="upload.xml">
<button class="btn-file-input" id="bt">Select a File to Share</button>
<input type="file" name="file" multiple />
</form>
<br/><br/>
<div id="response"></div>
</div>
JAVASCRIPT
(function () {
var input = document.getElementById("file"),
formdata = false;
function showUploadedItem(source) {
document.getElementById("image-list").innerHTML = "<li><img src='" + source + "' /></li>";
}
if (window.FormData) {
formdata = new FormData();
document.getElementById("bt").style.display = "inline";
}
input.addEventListener("change", function (evt) {
document.getElementById("response").innerHTML = "<div class='uploading'></div>"
var i = 0,
len = this.files.length,
img, reader, file;
formdata = new FormData();
file = this.files[i];
if (file.type.match(/file.*/)) {
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function (e) {
var source = e.target.result;
document.getElementById("image-list").innerHTML = "<li><img src='" + source + "' /></li>";
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file[]", file);
}
}
if (formdata) {
$.ajax({
url: "upload.xml",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
}
}, false);
})();
Initially, the code was functioning properly until I attempted to customize the file input field, which led to things breaking down. At this point, I am unsure of where my mistake lies.
You may also view the live version of the code at the following URL: cyogen.com