package com.jopek.submittodatiinator; import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.OpenableColumns; import android.util.Log; import java.io.DataOutputStream; import java.io.File; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Random; public class Requests { public static final String TAG = "REQUESTS"; static final String uploadServerUri = "https://jopek.eu/maks/submitto-dati-inator/upload.php"; private final static String lineEnd = "\r\n"; private final static String twoHyphens = "--"; public static ReturnValues uploadFile(Context context, Uri sourceFileUri) { final String boundary = "------------------------" + getRandomString(16); int serverResponseCode = 0; HttpURLConnection conn = null; DataOutputStream dos = null; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String filename = getFileName(context, sourceFileUri); // File sourceFile = new File(sourceFileUri); // if (!sourceFile.isFile()) { // Log.e(TAG, "Source File not exist :" + sourceFileUri); // return ReturnValues.NO_FILE; // } else { try { // open a URL connection to the Servlet // InputStream fileInputStream = new FileInputStream(sourceFile); InputStream fileInputStream = context.getContentResolver().openInputStream(sourceFileUri); URL url = new URL(uploadServerUri); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setChunkedStreamingMode(2048); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Authorization", "Basic maks:"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=" + filename + ";filename=" + filename + "" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necessary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i(TAG, "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); //close the streams fileInputStream.close(); dos.flush(); dos.close(); if (serverResponseCode != 200) return ReturnValues.SERVER_ERROR; } catch (MalformedURLException e) { e.printStackTrace(); Log.e(TAG, "error: " + e.getMessage(), e); return ReturnValues.MALFORMED_URL; } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "Exception : " + e.getMessage(), e); return ReturnValues.SERVER_ERROR; } return ReturnValues.OK; // } } public static String getRandomString(int length) { int leftLimit = 48; // numeral '0' int rightLimit = 122; // letter 'z' Random random = new Random(); return random.ints(leftLimit, rightLimit + 1).filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)).limit(length).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString(); } @SuppressLint("Range") public static String getFileName(Context context, Uri uri) { String result = null; if (uri.getScheme().equals("content")) { Cursor cursor = context.getContentResolver().query(uri, null, null, null, null); try { if (cursor != null && cursor.moveToFirst()) { result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); } } finally { cursor.close(); } } if (result == null) { result = uri.getPath(); int cut = result.lastIndexOf('/'); if (cut != -1) { result = result.substring(cut + 1); } } try { return URLEncoder.encode(result, String.valueOf(StandardCharsets.UTF_8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } public enum ReturnValues { OK, NO_FILE, MALFORMED_URL, SERVER_ERROR, } }