Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import android.util.Base64;
import android.util.Log;

public class Main {
    private final static String TAG = "";

    public static String uploadFile(String path) {
        String sourceFileUri = path;
        File file = new File(sourceFileUri);
        ByteArrayOutputStream objByteArrayOS = null;
        FileInputStream objFileIS = null;
        boolean isSuccess = false;
        String strAttachmentCoded = null;

        if (!file.isFile()) {
            Log.w(TAG, "Source File not exist :" + sourceFileUri);
        } else {
            try {
                objFileIS = new FileInputStream(file);
                objByteArrayOS = new ByteArrayOutputStream();
                byte[] byteBufferString = new byte[(int) file.length()];
                objFileIS.read(byteBufferString);

                byte[] byteBinaryData = Base64.encode(byteBufferString, Base64.DEFAULT);
                strAttachmentCoded = new String(byteBinaryData);

                isSuccess = true;
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("Upload file to server", "error: " + e.getMessage(), e);
            } finally {
                try {
                    objByteArrayOS.close();
                    objFileIS.close();
                } catch (IOException e) {
                    Log.e(TAG, "Error : " + e.getMessage());
                }
            }
        }

        if (isSuccess) {
            return strAttachmentCoded;
        } else {
            return "No Picture";
        }
    }
}