Saturday, March 16, 2013

iMapIt Pro 2.0 – How the Transferring of a File Exported to a Web Site Works

One of the main functionalities of the version iMapIt Pro 2.0 is to allow the file to be exported, available now on formats DXF, KML or GPX. Besides being able to be extracted through cable, by USB Port and sent by e-mail, it can also be sent through internet to an internet server.

The main goal of this article is to explain how the functionality of  sending the file through internet can be used.

When tapping on option "Web" under "Send to:" a field will be shown right under it and which will allow you to type the internet address to where the file must be sent.


When tapping on Export button, the file will be sent to the address informed and a screen will be shown with the answer from the server.


Notice that to apply it correctly, the server indicated on the internet address, must be ready to receive the file. Then, you must have access to this server, so that you can configure it and receive the file and save it where you find it appropriated on the server.
How do I configure the server to receive the file?
I developed two examples of scripts to internet servers that may be used to receive the file sent by iMapIt Pro.
The first example is a script PHP. PHP is one of the programming languages for internet servers. This type of file works on Apache servers.
See the example below, the file must be saved under the name "imapit_uploader.php".


------------------------------------------------------------- Beginning of PHP file (do not include this line)


<?php

// iMapIt Uploader
// Example of PHP script to upload the export file sent by iMapIt

// Folder where the file will be saved
$_UP['pasta'] = 'uploads/';

// File maximum size (in Bytes)
$_UP['tamanho'] = 1024 * 1024 * 2; // 2Mb

// Array with allowed file extensions
$_UP['extensoes'] = array('dxf', 'kml', 'gpx');

// Rename file? (If true, file will be saved with a unique name.jpg)
$_UP['renomeia'] = false;

// Array with PHP upload common error description
$_UP['erros'][0] = 'Successful upload';
$_UP['erros'][1] = 'File size is greater than PHP limit';
$_UP['erros'][2] = 'File size is greater than the limit specified in HTML';
$_UP['erros'][3] = 'Partial file upload';
$_UP['erros'][4] = 'File not uploaded';

// Return html header
echo "<br><br><br>--- iMapIt Uploader ---<br>File: " . $_FILES['iMapIt_File']['name'] . "<br><br>";

// Check if there were any upload error. If yes, show error message.
if ($_FILES['iMapIt_File']['error'] != 0) {
die("It was not possible to upload the file, error:<br />" . $_UP['erros'][$_FILES['iMapIt_File']['error']]);
exit; // Stop script execution
}

// If the script got to this point there was no upload error and the PHP script can continue

// Check if it is a allowed file extension
$extensao = strtolower(end(explode('.', $_FILES['iMapIt_File']['name'])));
if (array_search($extensao, $_UP['extensoes']) === false) {
    echo "Please, the only allowed file extensions are: dxf, kml ou gpx";
}

// Check file size
else if ($_UP['tamanho'] < $_FILES['iMapIt_File']['size']) {
echo "Uploaded file is to big. Send only files up to 2Mb.";
}

// File passed all checks. Time to move it to the destination folder.
else {
// First, change the file name, if needed.
if ($_UP['renomeia'] == true) {
    // File name with UNIX TIMESTAMP plus .jpg extension
    $nome_final = time().'.jpg';
} else {
    // Keep the original file name
    $nome_final = $_FILES['iMapIt_File']['name'];
}

// Check if it is possible to move the file to the destination folder
if (move_uploaded_file($_FILES['iMapIt_File']['tmp_name'], $_UP['pasta'] . $nome_final)) {
    // File successfuly uploaded
    echo "Upload successful!";
    } else {
        // It was not possible to upload the file, may be some issue with destination folder
        echo "It was not possible to upload the file, please try again";
    }
}
?>
---------------------------------------------------------------- End of PHP file (do not include this line)

You will only need one type of script on the internet server, let us show you another example, now in JSP. JSP is another type of programming language for internet servers and works on Apache Tomcat Servers.
See the example below, the file must be saved under the name "imapit_uploader.jsp".

------------------------------------------------------------- Beginning of JSP file (do not include this line)

<%@ page language="java" contentType="text/html;charset=utf-8"%>
<%request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");%>
<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>
<%
File file;
int MAX_FILE_SIZE = 5 * 1024 * 1024;
int MAX_MEM_SIZE = 1 *1024 * 1024;
ServletContext context = pageContext.getServletContext();
String tempFolder = context.getInitParameter("temp-folder");
String IMEI="", method="", msg="";
boolean isMultipart;
method = request.getMethod();
isMultipart = ServletFileUpload.isMultipartContent(request);

if (isMultipart && method.equalsIgnoreCase("POST")) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(MAX_MEM_SIZE);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File(tempFolder));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(MAX_FILE_SIZE);
List items = null, fileItems = null;
FileItem item;
String fileName="";
try {
items = upload.parseRequest(request);
Iterator itr = items.iterator();
int idx;
while (itr.hasNext()) {
item = (FileItem) itr.next();
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase("IMEI")) 
IMEI = item.getString() + "";
} else {
if (fileItems==null) fileItems = new ArrayList<FileItem>();
fileItems.add(item);
}
}
//if (IMEI.equals("") || IMEI.equals("null")) {
// msg = "Invalid source";
//}
if (fileItems!=null && !fileItems.isEmpty()) {
msg = "You have uploaded following file(s): ";
for (int i=0; i<fileItems.size(); i++) {
item = (FileItem) fileItems.get(i);
fileName = item.getName();
idx = fileName.lastIndexOf("\\");
if (idx == -1) idx = fileName.lastIndexOf("/");
if (idx >= 0) {
fileName = fileName.substring(idx);
}
fileName = fileName;
item.write(new File(tempFolder + fileName));
msg += "<br><a href=\"/upload/temp/" + fileName + "\">" + fileName + "</a>";
}
}
} catch (Exception e) {
msg = e.getMessage();
}
} else {
msg += "Upload is not accepted.<br>";
msg += "Please upload file using multipart/form-data and POST method<br>";
}
%>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>KML Loader</TITLE>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</HEAD>
<BODY>
<%=msg%>
</BODY>
</HTML>

---------------------------------------------------------------- End of JSP file (do not include this line)


If someone has more script examples to share, they will be more than welcome.

Well, in order to test if your upload script is working properly, you can use the HTML code; you can see as an example below. This code can be saved under the name "teste_upload.html".


---------------------------------------------------------------- Beginning of HTML file (do not include this line)

<!DOCTYPE HTML>
<HTML>
    <HEAD>
            <TITLE>iMapIt Loader Test</TITLE>
            <META http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </HEAD>
    <BODY>
            <FORM id="frm" name="iMapIt_Form" action="imapit_uploader.php" method="POST" enctype="multipart/form-data">
                Select a file to upload<br>
                <INPUT id="iMapIt_File" name="iMapIt_File" type="file" style="width:100%;"/><br>
                <INPUT id="submit" type="submit" value="Submit" />
                </FORM>
    </BODY>
</HTML>

---------------------------------------------------------------- End of HTML file (do not include this line)


The HTML file example above is how the iMapIt Pro from your iPhone or iPad will transfer the exported file. If the test file above works calling the PHP script "imapit_uploader.php" and transfer a file properly; the iMapIt Pro will also work.

Feel free to send questions and suggestions.