0

I have tried the following link:

https://stackoverflow.com/a/35465318/787399

But I never receive onSuccess callback.

More: when I upload more than one file [images], then only one file gets uploaded, the other are posted blank.

More: when using usual HTTPClient APIs I was getting duplicate files at the other end, therefore I switched to this library from loopj. This library also has its set of issues however.

1 Answer 1

0

Here is the code which help You.

public class uploadFiles extends AsyncTask<Void, Void, String> {
        private final ProgressDialog dialog = new ProgressDialog(
                PtoPPostActivity.this);
        protected void onPreExecute() {
            this.dialog.setMessage("Loading...");
            this.dialog.setCancelable(false);
            this.dialog.show();
        }
        @Override
        protected String doInBackground(Void... params) {
           String result=uploadFile(""); // inside the method paste your file uploading code
            return result;
        }
        protected void onPostExecute(String result) {
            // Here if you wish to do future process for ex. move to another activity do here
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            showDialog(PtoPPostActivity.this,result);
        }
    }

public String uploadFile(String req) {
        // TODO Auto-generated method stub

        String serverResponseMessage = "";
        String response_return = "";
        Log.d("first str is:", req);

        URL imageUrl = null;
        try {
            imageUrl = new URL(Constant.WEBSERVICE_URL); // get WebService_URL
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "---------------------------14737809831466499882746641449";
        // generating byte[] boundary here

        HttpURLConnection conn = null;
        DataOutputStream outputStream = null;

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

        try {
            int serverResponseCode;
            conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            // json String request
            outputStream = new DataOutputStream(conn.getOutputStream());

            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"json\"" + lineEnd);
            outputStream.writeBytes("Content-Type: text/plain;charset=UTF-8" + lineEnd);
            outputStream.writeBytes("Content-Length: " + req.length() + lineEnd);
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(req + lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);

            // image
            Log.i("images path==>", "" + imageArry); // get photo
            // local path

            for (int i = 0; i < imageArry.size(); i++) {
                try {
                    String filePath = imageArry.get(i).get("uploadedPath");
                    Log.d("filePath==>", imageArry.get(i).get("uploadedPath") + "");

                    //////////////////////////////////////////////////
                    //  Bitmap original = BitmapFactory.decodeFile(mFileTemp.getPath());
                    Bitmap original = BitmapFactory.decodeFile(filePath);
                    if (original != null) {
                        Bitmap newBitmap = original;

                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                        byte[] bitmapdata = stream.toByteArray();

                        File cacheDir = PtoPPostActivity.this.getCacheDir();
                        File f = new File(cacheDir, "temp" + i + ".jpeg");
                        //write the bytes in file
                        FileOutputStream fos = new FileOutputStream(f);
                        fos.write(bitmapdata);
                        FileInputStream fileInputStream = new FileInputStream(f);
                        String lastOne = "temp";
                        /////////////////////////////////////////////

                        outputStream.writeBytes(twoHyphens + boundary + lineEnd);

                        outputStream.writeBytes("Content-Disposition: attachment;  name=\"imagePath" + i + "\"; filename=" + lastOne + i + ".jpeg" + lineEnd); // pass key & value of photo

                        outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd);
                        outputStream.writeBytes(lineEnd);

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

                        // Read file
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                        while (bytesRead > 0) {
                            outputStream.write(buffer, 0, bufferSize);

                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                        }

                        outputStream.writeBytes(lineEnd);

                        Log.d("posttemplate", "connection outputstream size is " + outputStream.size());
                        fileInputStream.close();
                    }
                } catch (OutOfMemoryError o) {
                    continue;
                }
            }

            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            serverResponseCode = conn.getResponseCode();
            serverResponseMessage = conn.getResponseMessage();

            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response1 = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response1.append(line);
                response1.append('\r');
            }

            rd.close();
            response_return = response1.toString();

            Log.d("posttemplate", "server response code " + serverResponseCode);
            Log.d("posttemplate", "server response message "
                    + serverResponseMessage);
            outputStream.flush();
            outputStream.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            Log.d("posttemplate", "malformed url", e);
            // Toast.makeText(getApplicationContext(),e.toString(),
            // Toast.LENGTH_LONG).show();
            // TODO: catch exception;
        } catch (IOException e) {
            Log.d("posttemplate", "ioexception", e);
            // Toast.makeText(getApplicationContext(),e.toString(),
            // Toast.LENGTH_LONG).show();
            // TODO: catch exception
        }
        Log.d("response--->", "****" + response_return);
        global_response = response_return;
        return response_return;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.