[HOWTO] Use AJAX to send a file through a form

As you know, AJAX is used to asynchronously transfer information from the client to the server without refreshing the web page. You normally use it as follows:

1) Client side HTML form code:

<div id="formulary">
<form name="example" method = "POST" enctype="multipart/form-data" onsubmit="send_form()">
<input type="text" name="param1">
<input type="text" name="param2">
<input type="submit" value="Cargar archivo" />
</form>
</div>

2) Client side AJAX script (Javascript):

<script>
function send_form(){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4){
if (xmlhttp.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("divresponse").innerHTML=xmlhttp.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
//parameters for the POST request
var parameter1 =encodeURIComponent(document.getElementById("parameter1").value);
var usuariovalue=encodeURIComponent(document.getElementById("parameter2").value);
var parameters="parameter1"="+ parameter1+"&amp; parameter2="+ parameter2;

//open asynchronous connection, indicating the sending method, the webpage receiver, and “true”, which means the proper asynchronous sending
xmlhttp.open(“POST”, “sendform.php”, true);
xmlhttp.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
xmlhttp.send(parameters);
}

2) Server side (PHP, for example):

<?php
echo 'parameters: ' . $_POST['parameter1'] . $_POST['parameter2']
?>

But the problem is that XMLHttpRequest was not thought to send a file within. There are different implementations to solve it, the most extended one is shown below. It consists on reloading the page into an invisible , sending the output from the form into this :

1)Client side (HTML):

<div id="message"></div>

2)Server side (PHP):

<?php
$tmp = $_FILES['fichero']['tmp_name'];
//check if the file has been sent
if(isset($_FILES['fichero'])){
//definitely file route (where you want the file to be stored into the server)
$name = "../folder/" . $_FILE['usuario'] . end(explode(".", $tmp)+1);
if(move_uploaded_file($tmp, $name)){
//the file has been succesfully received and stored
echo '
<script>
parent.document.getElementById("mensaje").innerHTML="file received";
new_f.type="file";
new_f.name="fichero";
new_f.value="";
new_f.id="fichero";
new_f.onchange=function(){
parent.document.getElementById("message").innerHTML="";
}
old_f.parentNode.replaceChild(new_f,old_f);
</script>';
exit;
}
}
?>
Advertisements

[Java] [Singleton Pattern] Why using Public classes with Private constructors?

We can find an example of a Public class with Private constructor below:

public class Products {

private static List<Product> listProducts = new ArrayList<Product>();
static {
for (int i = 0; i<19; i++) {
listProducts.add(new Producto(i, “producto ” + i));
}
}

private Products() {}

}

If we try to cast an instance of the class above we will obtain the following error:

GestionProductos example = new GestionProductos();

Error: The constructor GestionProductos() is not visible

So, how can we use this kind of class, and more important, why? well, the answer is simple. The designer has done the class in this way because he/she doesn’t want the class to be instanced. Although most of the times this behavior is a whimsy decission, it is a good practice for (like the class from the example above) a component delivered to a third, which is going to be forced to use only one instance from the class, avoiding unnecesary and memory spending copies from that class. For example, the class above is going to simulate the persistence layer, and we only want one copy of this layer,and the properties from the class are only accessible by the public setters and getters from the same class, like the following example:

List <Producto> listadoProducts = Products.getProducts();

This coding practice is called Singleton Pattern, or unique instance (the designers ensures that the class is going to be instanced only once).

Another use of a Public class with one private constructor could be, for example, to be instanced using other overloaded constructors, and these constructors would call the private constructor.