0

My code is below.

After uploading (time is varying for different file sizes) I got 200 Ok and response

public class CloudFileUploader extends AsyncTask<String, Void, String> {



@Override
protected String doInBackground(String... params) {

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    int serverResponseCode = 0;
    try {
        FileInputStream fileInputStream = new FileInputStream(mFile);
        URL url = new URL(CloudConstants.getFileUploadBaseUrl());
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary + ";key=fileToUpload");
        conn.setRequestProperty("Accept", "application/json");
        String contentLength=Long.toString(mFile.length());
 //            conn.setRequestProperty("Content-Length",contentLength );

        AppSharedPreference mPref = new AppSharedPreference(mContext);
        String token = mPref.getStringPrefValue(PreferenceConstants.USER_TOKEN);
        conn.setRequestProperty("token", token);
        conn.setRequestProperty("groupId", "" + mMessage.getReceiverId());
        conn.setRequestProperty("message", "" + mMessage.getMessageBody());
        conn.setRequestProperty("messageType", "" + mMessage.getMessageType());
        conn.setRequestProperty("senderName", "" + mMessage.getSenderName());

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

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + mFile.getName() + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        Log.i(TAG, "Initial .available : " + bytesAvailable);

        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(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        serverResponseCode = conn.getResponseCode();
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException | FileNotFoundException | ProtocolException ex) {
        ex.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (serverResponseCode == 200) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn
                    .getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            if (onFileUploadListener != null) {
                onFileUploadListener.onUploadFailed(mMessage, new AppError(ErrorHandler.ERROR_FROM_SERVER, ErrorHandler.ErrorMessage.ERROR_FROM_SERVER));
            }
        }
        return sb.toString();
    } else {
        return "Could not upload";
    }
}
}

I put conn.setRequestProperty("Content-Length",contentLength ); but it will throw java.net.ProtocolException.

I tested differnt code but the issue is still there.

Below given is my php server script.

$status['apiId'] = _GROUP_FILE_UPLOAD_API;
    $user_id = $this->user['user_id'];
    $target_dir = ROOTDIR_PATH . DS . "data" . DS . "GroupFileUploads" . DS;
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
     $fileUpload = NULL;
    if ($this->headers->get('groupId')) {
        $fileUpload['groupId'] = $groupId = $this->headers->get('groupId')->getFieldValue();
    }
    if ($this->headers->get('messageType')) {
        $fileUpload['messageType'] = $messageType = $this->headers->get('messageType')->getFieldValue();
    } if ($this->headers->get('message')) {
        $fileUpload['message'] = $message = $this->headers->get('message')->getFieldValue();
    }
    if ($this->headers->get('senderName')) {
        $fileUpload['senderName'] = $senderName = $this->headers->get('senderName')->getFieldValue();
    }

The code is not working. It is not saving anything to the folder I given.

But It is working from Postman and AdvancedRestClient

When I put die() then i Got

Array( [myFile] => Array ( [name] => 1495018448FaceApp_1494992050886.jpg [type] => [tmp_name] => /tmp/phpH2kH47 [error] => 0 [size] => 917953 ))

The [type] => should be image/jpg but it is empty

noobEinstien
  • 3,147
  • 4
  • 24
  • 42
  • 1
    Why are you not using [HttpClient](http://stackoverflow.com/questions/4126625/how-do-i-send-a-file-in-android-from-a-mobile-device-to-server-using-http)? – litelite May 16 '17 at 12:37
  • Hi @Godwin its possible duplicate. Kindly check this out. http://stackoverflow.com/questions/25398200/uploading-file-in-php-server-from-android-device – Rameshbabu May 16 '17 at 12:39
  • Why do you put some text in quote blocks..? – Denny May 16 '17 at 12:40
  • It should be dos.write(buffer, 0, bytesRead); – greenapps May 16 '17 at 12:46
  • Do the flush before you ask for a response code. And do not close the output stream. – greenapps May 16 '17 at 12:47
  • You catch a lot of exceptions. Which is good. But if you have one you just continue with the code as if nothing has happened. Instead you should return an error message there and display the message in onPostExecute. – greenapps May 16 '17 at 12:50
  • @Rameshbabu yes Bro its the copy code, but its not working – noobEinstien May 16 '17 at 13:42
  • @greenapps Oops its also not working. and in every example, they are not using `bytesToRead` instead of that they are using `bufferSize` because the third paraaeter is length – noobEinstien May 16 '17 at 13:45
  • That parameter will not make it work i know. But if you get it to work then you will see that you have to use bytesRead as you should specify the amount of bytes to be written. Which is bytesRead. Dont write more bytes then you read. And all examples are wrong of course. – greenapps May 16 '17 at 15:07
  • What about the flush and the close? – greenapps May 16 '17 at 15:08
  • Its is not the byte array or buffersize , All are fine when I put die on php, then I got the file name and properties but the type is bot printing – noobEinstien May 17 '17 at 10:58

0 Answers0