0

I am able to upload image without using GZIPOutputStream to server. But i have requirement to use GZIPOutputStream. So i have used by :

public String multipartRequest(String urlTo, String post, String filepath, String filefield) throws ParseException, IOException {
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;

    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    String lineEnd = "\r\n";

    String result = "";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    String[] q = filepath.split("/");
    int idx = q.length - 1;

    try {
        File file = new File(filepath);
        FileInputStream fileInputStream = new FileInputStream(file);

        // code my
        byte[] data = new byte[(int) file.length()];

        URL url = new URL(urlTo);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        // connection.setRequestProperty("Content-Encoding", "gzip");

        outputStream = new DataOutputStream(connection.getOutputStream());

        // outputStream.writeBytes("HTTP/1.1 200 OK\r\n");
        // outputStream.writeBytes("Content-Type: application/x-gzip");

        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + ".gz" + "\""
                + lineEnd);
        // outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" +
        // q[idx] + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        // buffer = new byte[bufferSize];

        bytesRead = fileInputStream.read(data, 0, bufferSize);
        while (bytesRead > 0) {
            outputStream.write(data, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(data, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);

        // Upload POST Data
        String[] posts = post.split("&");
        int max = posts.length;
        for (int i = 0; i < max; i++) {
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            String[] kv = posts[i].split("=");
            outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + ".gz" + "\"" + lineEnd);
            // outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(kv[1]);
            outputStream.writeBytes(lineEnd);
        }
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // For GZip outputStream //

        try (GZIPOutputStream gzos = new GZIPOutputStream(outputStream)) {
            gzos.write(data);
            gzos.close();
            Log.v("GZip", "Working");
        } catch (IOException e) {
            Log.v("TraceError", e.getMessage().toString());
            e.printStackTrace();
        }

        // end
        inputStream = connection.getInputStream();
        result = this.convertStreamToString(inputStream);
        Log.v("MYRESULT", result);

        fileInputStream.close();
        inputStream.close();
        outputStream.flush();
        outputStream.close();
        return result;
    } catch (Exception e) {
        Log.e("MultipartRequest", "Multipart Form Upload Error");
        e.printStackTrace();
        return "error";
    }

}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

Here I am able to see

Log.v("GZip", "Working");

means file is compressed but image is not uploading to server.

I am not able to see this statement means not getting success. Also i m not getting any kind of error , warning etc nothing.

Log.v("MYRESULT", result);

So can anyone have a idea? Advanced help would be appreciated !

2 Answers2

0

You are not reading the inputstream correctly onto data. You are overwriting it on every loop. Change the code to

int totalBytesRead = 0;
bytesRead = fileInputStream.read(data, 0, data.length); 
while (bytesRead > 0) { 
    totalBytesRead += bytesRead;  
    bytesRead = fileInputStream.read(data, totalBytesRead, data.length - totalBytesRead);
}
outputStream.write(data);
lionscribe
  • 3,413
  • 1
  • 16
  • 21
  • I just fixed it. Your code seemed to have gone through many revisions, and was messy. – lionscribe Aug 11 '16 at 05:18
  • By the way, are you planning to always send it up twice, or is it only for testing? For if you are only sending once, then you could skip all the comments I wrote, and read into buffer (not data) and write to stream, in each loop. – lionscribe Aug 11 '16 at 05:25
0

Finally i have solved with myself.!

I was doing mistake here !

outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + ".gz" + "\"" + lineEnd);

I was appending ".gz" to other form data. I only needed to append file name.

Its really a silly !

  • You still have a bug in your code, as I answered below. It works now, for it seems to read the whole stream in one loop, but will break if it does it in two or more loops. – lionscribe Aug 11 '16 at 05:07