I'm trying to locate an image file stored on my computer in a windows 8 Javascript app and post it through WinJS.xhr to a Java servlet in which the data is inserted into a mysql database.
The cause of the problem could be when either 1) sending the data through the .xhr method by using as parameter encodeURIComponent(evt.target.result) or 2) when inserting this data via the Java servlet to the mysql db. The error actually occurs at 2) because it only inserts null values when 1) is used, but for other values the servlet works perfectly (see Ad 2).
Ad 1): I'm not sure if using encodeURIComponent(evt.target.result) in the following context is an appropriate way to get the content of a stored file and prepare it for a post request:
document.getElementById("btnUpload").onclick = function () {
var input = document.getElementById("file_input");
readFile(input.files[0], function(file, evt)
{
WinJS.xhr({
type: "post",
url: "http://servlett.domain.com:8080/Servlet/addImage",
headers: { "Content-type": "application/x-www-form-urlencoded" },
data: "fk_floor_id=" + currentFloorId + "&map=" + encodeURIComponent(evt.target.result)
}).then(
function (xhr) {
var success = xhr.response;
}, function (xhr) {
var error = xhr.response;
}
);
});
The parameter evt.target.result is retrieved through the following method:
function readFile(file, callback) {
var reader = new FileReader();
reader.onload = function (evt) {
if (typeof callback == "function")
callback(file, evt);
};
reader.readAsText(file);
}
where file_input is a input component inside the following form:
<form action="" method="post">
<input type="file" id="file_input" />
<button type="button" id="btnUpload">Upload</button>
</form>
By the way: This way of doing so I got from the following tutorial for file upload per javascript: http://www.tutorials.de/content/1239-file-upload-per-javascript-html-5-file-api.html
Ad 2) Now my servlet listens and processes the data, but he only stores null values into the db. If I remove the parameter "&map=" + encodeURIComponent(evt.target.result) from 1) and replace it with "&map=test" the servlet perfectly stores the values into the database. Here the servlet code:
stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO maps (fk_floor_id,map) VALUES ("+request.getParameter("fk_floor_id")+",'"+request.getParameter("map")+"')");
The attribute maps is defined as a blob inside mysql.
Maybe someone sees the error or could tell me how to upload an image in javascript in a different manner.