0

So I have done this earlier multiple times using the MultiPartEntity in apache implementations but now with the deprecation of the APIs I need to use HTTPUrlConnection.

My Server side script looks something like this in php

    $userData = urldecode ( $_POST['form'] );
    $json = json_decode ( $userData );
    $username = $json->emailAddress;
    $this->load->model( 'rest_image_upload_model' );
    $result = $this->rest_image_upload_model->checkCredentialsAndReturnUserId ($username, $password);
    $userId = $result ['mfwid'];

    if($userId == 0 || empty($userId) || false == $result){
        $responseJson['success'] = false;
        $responseJson['message'] = "Username could not be fetched. Contact system admin.";
        echo json_decode($responseJson);
        return;
    }

    $firstName = '';
    $result = $this->rest_image_upload_model->fetchUsersName( $userId );
    $firstName = $result ['first_name'];

    if(empty($firstName) || false == $result){
        $responseJson['success'] = false;
        $responseJson['message'] = "First Name could not be fetched. Contact system admin.";
        echo json_decode($responseJson);
        return;
    }
    //end of json part

    // Start creating a floder for the image to be uploaded
    $foldername = $firstName . '-' . $userId;
    if (! is_dir ( 'download/upload/profile/' . $date . '/' . $foldername )){
        mkdir ( './download/upload/profile/' . $date . '/' . $foldername, 0777, TRUE );
   }
    $config ['upload_path'] = './download/upload/profile/' . $date . '/' . $foldername;
    $thumbnailRefFilePath = $config['upload_path'];
    $config ['allowed_types'] = "jpg|png|JPEG|jpeg|PNG|JPG"; // 'gif|jpg|png|tiff';
    $config ['max_size'] = '10240';
    $config ['max_width'] = '5000';
    $config ['max_height'] = '5000';
    $this->load->library ( 'upload', $config );
    $this->upload->initialize ( $config );
    if (! $this->upload->do_upload ( 'image' )) { // if uploading image failed
        $responseJson['success'] = false;
        $responseJson['message'] = "File Not Uploaded";
        //$upload_data['file_name']='nopic.png';
        echo json_encode($responseJson);
        return;
    } else { 

        // uploading image success
        $upload_data = $this->upload->data(); // save
      }

The Android code seems to upload the json part but I get the error. File not uploaded in a json. Below is my android code for this.

public StringBuilder doMultipartPost(String api,
                                         String jsonPost,
                                         String jsonPartKey,
                                         String filePath,
                                         String filePathKey) throws InstyreNetworkException{

        String boundary = UUID.randomUUID().toString();
        String twoHyphens = "--";
        //String attachmentName = "data";
        String crlf = "\r\n";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;

        try {
            final String URL = NetworkUtils.BASE_URL + api;
            URI uri = new URI(URL);
            HttpURLConnection urlConnection = (HttpURLConnection) uri.toURL().openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());

            // FIRST PART; A JSON object
            dos.writeBytes(twoHyphens + boundary);
            dos.writeBytes(crlf);
            dos.writeBytes("Content-Type: application/json");
            dos.writeBytes(crlf);
            dos.writeBytes("Content-Disposition: form-data; name=\""+jsonPartKey+"\"");
            dos.writeBytes(crlf);
            dos.writeBytes(crlf);
            dos.writeBytes(jsonPost);
            dos.writeBytes(crlf);

            // SECOND PART; A image..
            File file = new File(filePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            dos.writeBytes(twoHyphens + boundary);
            dos.writeBytes(crlf);
            dos.writeBytes("Content-Type: jpg");
            dos.writeBytes(crlf);
            dos.writeBytes("Content-Disposition: form-data; name=\"image\"");
           // dos.writeBytes("Content-Disposition: form-data; name=\"attachment_0\";filename=\"" + file.getName() + "\"" + lineEnd);
            dos.writeBytes(crlf);
            dos.writeBytes(crlf);
            dos.writeBytes("Content-Length: " + file.length() + crlf);
            dos.writeBytes(crlf);
            dos.writeBytes(crlf);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            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);
            }

            dos.writeBytes(crlf);
            dos.writeBytes(twoHyphens + boundary + crlf);
            fileInputStream.close();

            // start reading response
            InputStream is = urlConnection.getInputStream();
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);
            is.close();
            dos.close();
        } catch (Exception e) {
             e.printStackTrace();
        }
        return null;
    } 
ichthyocentaurs
  • 2,173
  • 21
  • 35
  • Try to use Android [Volley](https://developer.android.com/training/volley/simple.html) – dieter_h Sep 03 '15 at 19:46
  • here is the link https://github.com/mcxiaoke/android-volley – Sony Sep 03 '15 at 19:51
  • https://code.google.com/p/httpclientandroidlib/ follow links to apache impl of the legacy packages that you lost access to... IMO no reason to have to refactor to httpUrlConn when you can stay on httpClient like you had.. just switch over to the Apache.httpClient package. code will not have to change much just some classes u have to add the "HC4" suffix or adjust to their Namespace. – Robert Rowntree Sep 03 '15 at 20:07
  • The thing is HTTPUrlConnection is capable of performing uploads, also I am able to upload using a Rest Client. And my lead needs me to do it only using the HTTPUrlconnection, where the entire project space has been moved. Cant use volley, because we want to have our own implementation of network utilities which we can expand to add functionality later. – ichthyocentaurs Sep 03 '15 at 20:12
  • Ok so My server is giving the error {"success":false,"message":"File Not Uploaded, Error Code -

    You did not select a file to upload.

    "}
    – ichthyocentaurs Sep 03 '15 at 21:10
  • You can use Volley, refer to [this question](http://stackoverflow.com/questions/32240177/working-post-multipart-request-with-volley-and-without-httpentity) – BNK Sep 04 '15 at 04:59
  • 'Server side script looks something like this in php'. Something like this? What's that? Please post real code. And do you know why your script replies with the message that you did not select a file? Do away with this script first. Make a much simpler script where you only echo the received data. You should first know if you receive all ok. – greenapps Sep 04 '15 at 07:17

1 Answers1

-1

I found the part solution here http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically

public StringBuilder doMultipartPost(String api,
                                         String jsonPost,
                                         String jsonPartKey,
                                         String filePath,
                                         String filePathKey) throws NetworkException{

    String boundary = UUID.randomUUID().toString();
    String twoHyphens = "--";
    String crlf = "\r\n";

    try {
        final String URL = NetworkUtils.BASE_URL + api;
        URI uri = new URI(URL);
        HttpURLConnection urlConnection = (HttpURLConnection) uri.toURL().openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Connection", "Keep-Alive");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        OutputStream outputStream =  urlConnection.getOutputStream();
        DataOutputStream dos = new DataOutputStream(outputStream);

        // FIRST PART; A JSON object
        dos.writeBytes(twoHyphens + boundary);
        dos.writeBytes(crlf);
        dos.writeBytes("Content-Type: application/json");
        dos.writeBytes(crlf);
        dos.writeBytes("Content-Disposition: form-data; name=\""+jsonPartKey+"\"");
        dos.writeBytes(crlf);
        dos.writeBytes(crlf);
        dos.writeBytes(jsonPost);
        dos.writeBytes(crlf);

        File uploadFile = new File(filePath);
        String fileName = uploadFile.getName();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"),
                true);
        writer.append("--" + boundary).append(crlf);
        writer.append(
                "Content-Disposition: form-data; name=\"" + filePathKey
                        + "\"; filename=\"" + fileName + "\"")
                .append(crlf);
        writer.append(
                "Content-Type: "
                        + URLConnection.guessContentTypeFromName(fileName))
                .append(crlf);
        writer.append("Content-Transfer-Encoding: binary").append(crlf);
        writer.append(crlf);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        writer.append(crlf);
        writer.append(twoHyphens + boundary + crlf);
        outputStream.flush();
        inputStream.close();

        writer.flush();

        // start reading response
        InputStream is = urlConnection.getInputStream();
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null)
            responseStrBuilder.append(inputStr);
        is.close();
        dos.close();
        return responseStrBuilder;
    } catch (Exception e) {
         e.printStackTrace();
    }
    return null;
}
ichthyocentaurs
  • 2,173
  • 21
  • 35