In this article, Jean-Michel gives a code example to upload attachments to Convertigo.



 
If you need to upload programmatically files to Convertigo server, this piece of code could be very useful.

Pre-requisites


1 – Setup a Convertigo Server running a project "UploadFileDemo" with a sequence expecting a file upload.
2 – Create an empty java project in your favorite development environment.
3 – Download the java example files from these links (MultiPartFileUploader.java and MultipartUtility.java).
4 – Add them to your blank project.
5 – Adapt MultiPartFileUploader.java to your environment by setting the path to the file repository, Convertigo Server url etc…
6 – Test

MultipartFileUploader : usage of the MultipartUtility class

package com.convertigo.networking;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 *This program demonstrates a usage of the MultipartUtility class.
 *
 * @author www.codejava.net
 *
 */
public class MultipartFileUploader {
	public static void main(String[] args) {
		String charset = "UTF-8";
		File uploadFile2 = new File("<...pathtofile...>/tgv_high-spped_train_france.jpg");
		File uploadFile1 = new File("<...pathtofile...>/regional_train_in_italy.jpg");
		String requestURL = "http://C8oServer:28080/convertigo/projects/UploadFileDemo/.xml";

		try {
			MultipartUtility multipart = new MultipartUtility(requestURL, charset);
			multipart.addHeaderField("User-Agent", "Convertigo");

	/**
             * __sequence contains the name of the called sequence
             * within the specified project (in the requestURL)
             */
			multipart.addFormField("__sequence", "uploadFile");

	/**
            * uploadFilename is the name of the sequence
            * input variable in the called project
            *
            * the value is the name that will be given to the file
            */
			multipart.addFormField("uploadFilename", uploadFile1.getName());

			// not needed but helpful in logs
			multipart.addFilePart("uploadFilename", uploadFile1);
			// multipart.addFilePart("uploadFilename", uploadFile2);

			List<String> response = multipart.finish();

			System.out.println("SERVER REPLIED:");

			for (String line : response) {
				System.out.println(line);
			}
		} catch (IOException ex) {
			System.err.println(ex);
		}
	}
}

MultipartUtility : The upload utility itself (used as a library)

package com.convertigo.networking;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

/**
 * This utility class provides an abstraction layer for sending multipart HTTP
 * POST requests to a web server.

 *
 * @author www.codejava.net
 *
 */
public class MultipartUtility {
	private static final int CHUNKSIZE = 4096;
	private static final String LINE_FEED = "\r\n";
	private final String boundary;
	private HttpURLConnection httpConn;
	private String charset;
	private OutputStream outputStream;
	private PrintWriter writer;

/**
 * This constructor initializes a new HTTP POST request with content type is
 * set to multipart/form-data
 * 
 * @param requestURL
 * @param charset
 * @throws IOException
 */
	public MultipartUtility(String requestURL, String charset) throws IOException {
		this.charset = charset;

		// creates a unique boundary based on time stamp
		boundary = "===" + System.currentTimeMillis() + "===";

		URL url = new URL(requestURL);
		httpConn = (HttpURLConnection) url.openConnection();
		httpConn.setUseCaches(false);
		httpConn.setDoOutput(true); // indicates POST method
		httpConn.setDoInput(true);
		httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
		httpConn.setRequestProperty("User-Agent", "Convertigo Agent");
		
		outputStream = httpConn.getOutputStream();
		writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
	}

/**
 * Adds a form field to the request
 *
 * @param name
 * 		field name
 * @param value
 *		field value
*/
public void addFormField(String name, String value) {
		writer.append("--" + boundary).append(LINE_FEED);
		writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED);
		writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);
		writer.append(LINE_FEED);
		writer.append(value).append(LINE_FEED);
		writer.flush();
	}

/**
 * Adds a upload file section to the request
 * 
 * @param fieldName
 *		name attribute in <input type="file" name="..." />
 * @param uploadFile
 *		a File to be uploaded
 * @throws IOException
 */
	public void addFilePart(String fieldName, File uploadFile) throws IOException {
		String fileName = uploadFile.getName();
		writer.append("--" + boundary).append(LINE_FEED);
		writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED);
		writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
		writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
		writer.append(LINE_FEED);
		writer.flush();

		FileInputStream inputStream = new FileInputStream(uploadFile);
		byte[] buffer = new byte[CHUNKSIZE];
		int bytesRead = -1;
		
		while ((bytesRead = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, bytesRead);
		}
		
		outputStream.flush();
		inputStream.close();

		writer.append(LINE_FEED);
		writer.flush();
	}

/**
 * Adds a header field to the request.
 *
 * @param name
 * - name of the header field
 * @param value
 * - value of the header field
 */
	public void addHeaderField(String name, String value) {
		writer.append(name + ": " + value).append(LINE_FEED);
		writer.flush();
	}

/**
 * Completes the request and receives response from the server.
 *
 * @return a list of Strings as response in case the server returned status
 * 		OK, otherwise an exception is thrown.
 * @throws IOException
*/
	public List<String> finish() throws IOException {
		List<String> response = new ArrayList<String>();

		writer.append(LINE_FEED).flush();
		writer.append("--" + boundary + "--").append(LINE_FEED);
		writer.close();

		// checks server's status code first
		int status = httpConn.getResponseCode();
		if (status == HttpURLConnection.HTTP_OK) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				response.add(line);
			}
			reader.close();
			httpConn.disconnect();
		} else {
			throw new IOException("Server returned non-OK status: " + status);
		}

		return response;
	}
}

Conclusion

In conclusion, we see that Convertigo Mobility Platform is open to customization and lets you configure it in many ways although it is provided with many installed functionalities. We hope you enjoyed this article and see you on the forum to share with us your feedbacks.

Leave a comment