Child pages
  • Upload and download files
Skip to end of metadata
Go to start of metadata

Storing files

Apstrata relieves you from managing a file system or a database: using the store that is automatically associated to your Apstrata application, you can persist data of different types into documents Documents have a key/value pairs structure, where the key is a field name and the value can have one of the following types: string, numeric, text, date, geospatial and notably file.

To upload a file to your store, simply invoke the SaveDocument API and provide it with a document that contains a file. Apstrata documents have the predefined "apsdb_attachments" field that you can use to attach one or multiple files but you can also specify your own fields, which will require you to define a schema. To download your file, simply use the GetFile API, passing the names of the field and the attached file you would like to retrieve.

Back to the map       Next station: reuse your queries

Example 1: upload the player's picture to his persisted profile

You are currently implementing the next "unhappy poultry" mobile game and you think that it is cool to allow your players to upload a picture of themselves (or any other picture) to be used as an avatar in the game. Let us see how to do this using Apstrata. In the below example, we consider that we already created a profile document ("gangsta_profile") for a player named "gangsta", so we will issue a request to update this document by attaching the profile picture to the "apsdb_attachment" field.

 

curl -X POST "https://varick.apstrata.com/apsdb/rest/O763A7F690/SaveDocument?apsws.time=1418992125166" 
-F apsws.responseType=json -F apsdb_attachments=@my_avatar.png -F apsdb.documentKey=gangsta_profile 
-F apsdb.store=cabstore -F apsws.authSig=1933c4b633b2ad05c40c2bd7c7ad0aa8 -F apsdb.update=true
try {
	String authKey = "O763A7F690"; // Replace with your Application key
    String baseURL = "https://sandbox.apstrata.com/apsdb/rest";
                  
    // Sign your call with a signature based on your application key and secret  to authenticate against Apstrata
    // Simple signature is used in this example
    String secret = "S4A0120A6E64952FE75285BD0XD243S2"; // Replace with your application secret
    Connection ownerConnection = new OwnerConnection(baseUrl, authKey, secret);
    Client client = new Client(baseURL, authKey, ownerConnection);
 
	// Prepare the list of parameters to send along with the request
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
	BasicNameValuePair store = new BasicNameValuePair("apsdb.store", "DefaultStore"); // "DefaultStore" is the name by default. If you did not rename your store, this line is optional
	BasicNameValuePair docKey = new BasicNameValuePair("apsdb.documentKey", "gangsta_profile"); // We assume we already created a profile document using the player's name ("gangsta") + "_profile")
	BasicNameValuePair docKey = new BasicNameValuePair("apsdb.update", "true"); // We need to update the profile document by attaching the file
	parameters.add(store);
 	parameters.add(docKey);
	parameters.add(update);
	// Prepare a map of file fields and associate each file field with a list of files to upload
	HashMap<String, List<File>> filesMap = new HashMap<String, List<File>>();
	ArrayList<File> files = new ArrayList<File>();
	files.add(new File("path_to_my_avatar_pic/my_avatar.png")); // We only need to upload one file
	filesMap.put("apsdb_attachments", files); // We use the default "apsdb_attachments" field to attach our picture file to
	String response = client.callAPI("SaveDocument", parameters, filesMap, AuthMode.SIMPLE);
} catch (Exception e) {
	e.printStackTrace();
} finally {
	// do some stuff here
}
Try it!

Example 2: download the player's picture to his device

Let us see now how you can download the profile picture back to the device:

 

curl "https://varick.apstrata.com/apsdb/rest/O763A7F690/GetFile?apsws.time=1419003686629
&apsws.authSig=1933c4b633b2ad05c40c2bd7c7ad0aa8
&apsws.responseType=json&apsws.authMode=simple
&apsdb.fileName=my_avatar.png
&apsdb.store=DefaultStore
&apsdb.documentKey=gangsta_profile
&apsdb.fieldName=apsdb_attachments"
try {
	String authKey = "O763A7F690"; // Replace with your Application key
    String baseURL = "https://sandbox.apstrata.com/apsdb/rest";
                  
    // Sign your call with a signature based on your application key and secret  to authenticate against Apstrata
    // Simple signature is used in this example
    String secret = "S4A0120A6E64952FE75285BD0XD243S2"; // Replace with your application secret
    Connection ownerConnection = new OwnerConnection(baseUrl, authKey, secret);
    Client client = new Client(baseURL, authKey, ownerConnection);
 
	List<NameValuePair> parameters = new ArrayList<NameValuePair>();
	BasicNameValuePair docKey = new BasicNameValuePair("apsdb.documentKey", "gangsta_profile");
	BasicNameValuePair store = new BasicNameValuePair("apsdb.store", "DefaultStore");
	BasicNameValuePair fileField = new BasicNameValuePair("apsdb.fieldName", "apsdb_attachments");
	BasicNameValuePair fileName = new BasicNameValuePair("apsdb.fileName", "my_avatar.png");
	parameters.add(docKey);
	parameters.add(store);
	parameters.add(fileName);
	parameters.add(fileField);
	File responseFile = client.callAPIFile("GetFile", parameters, AuthMode.SIMPLE, "some_path");
} catch (Exception e) {
	e.printStackTrace();
} finally {
	// do some stuff here
}
Try it!

Example 3: save the player's picture only if smaller than 500Kb

Based on example 1 above, let us assume that you want to avoid excessive storage consumption and therefore, limit the size of the player picture to 500kb max. Hence, you need to check the size of the file before saving it into a document in your store. A solution is to do this in your Apstrata back-end, using a server-side script.

 

...
// Retrieve the files that are sent along the request
// using the native "request" object and its "files" property
var filesInRequest = request.files;
var params = {
	"apsdb.documentKey": request.parameters["documentKey"],
	"apsdb.update": "true",
	"apsdb.store": "cabstore"
};

// If files are available in the request, retrieve the ones that are associated 
// to the "picture" parameter (there can be more than one and therefore
// this results in an array) 
var attachedFilesArray = filesInRequest ? filesInRequest.picture : null;

// Since we should only have received one file, take the first file and store it in 
// the "pictureFile" variable. Otherwise, set this variable to null
var pictureFile = attachedFilesArray && attachedFilesArray.length > 0 ? attachedFilesArray[0] : null;
 
// Check the size of the file using the length property of the file object
if (pictureFile && pictureFile.size > (500 * 1024)) {
	return {
		"status": "failure",
		"errorCode": "INVALID_PIC_SIZE",
		"errorDetail": "The size of your profile picture should be less than 500K"
	}
} 
 
// If a file was found, we need to create a filesParam object that will be passed
// to SaveDocument. This object has the following structure:
// { attachment_fieldName1 : [array_of_files_to_attach], attachment_fieldName2 : [array_of_files_to_attach] }
var filesParam = pictureFile ? { 
	"apsdb_attachments": attachedFilesArray
} : null;

// Invoke the SaveDocument API and pass it the file
var response = apsdb.callApi("SaveDocument", params, filesParam);
if (response.metadata.status == "failure") {
	return response.metadata;
}
return response.result;
...
Try it!

Dig deeper

Related tutorials