tesy tesy - 2 months ago 9
Android Question

how to upload high resolution image in android to .net API server?

I am using below code to upload image to server but it is compressing image to lower resolution.

class ImageUploadTask extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {
ByteArrayBody bab;
ByteArrayOutputStream bos = new ByteArrayOutputStream();

URL url = new URL(webAddressToPost);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("enctype", "multipart/form-data");

MultipartEntity entity = new MultipartEntity();

signature_image.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] data = bos.toByteArray();
bab = new ByteArrayBody(data, contactNo+"_Signature.png");

entity.addPart("file", bab);
conn.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());

OutputStream os = conn.getOutputStream();
entity.writeTo(conn.getOutputStream());
os.close();
conn.connect();
}
}


How to upload high resolution image to server instead of compressed image?

Answer

Your code will compress the image and then uploading to server. Instead use below code to upload image with original resolution to server.

class ImageUploadTask extends AsyncTask<String, Integer, String> {
        private String webAddressToPost = "WRITE_YOUR_API_URL_TO_UPLOAD_IMAGE";

        @Override
        protected void onPreExecute() {
        }


        @Override
        protected String doInBackground(String... params) {
            String image_file_type = params[0];
            String file_name = params[1];
            int i=1;
            if (i==1){


                int day, month, year;
                int second, minute, hour;
                GregorianCalendar date = new GregorianCalendar();

                day = date.get(Calendar.DAY_OF_MONTH);
                month = date.get(Calendar.MONTH);
                year = date.get(Calendar.YEAR);

                second = date.get(Calendar.SECOND);
                minute = date.get(Calendar.MINUTE);
                hour = date.get(Calendar.HOUR);

                String name=(hour+""+minute+""+second+""+day+""+(month+1)+""+year);
                String tag=name+".jpg";



                    fileName = frontCameraImageUrl.replace(frontCameraImageUrl,tag);
                    sourceFile = new File(frontCameraImageUrl);

                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;


                if (!sourceFile.isFile()) {


                    Log.e("uploadFile", "Source File not exist :");


                    return "0";

                }
                else
                {
                    try {

                        // open a URL connection to the Servlet
                        FileInputStream fileInputStream = new FileInputStream(sourceFile);
                        URL url = new URL(webAddressToPost);

                        // 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.setRequestMethod("POST");
                        conn.setRequestProperty("Connection", "Keep-Alive");
                        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                        conn.setRequestProperty("uploaded_file", fileName);

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

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                + file_name + "\"" + 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 necesssary after file data...
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                        // Responses from the server (code and message)
                        int serverResponseCode = conn.getResponseCode();
                        String serverResponseMessage = conn.getResponseMessage();

                        Log.i("uploadFile", "HTTP Response is : "
                                + serverResponseMessage + ": " + serverResponseCode);

                        if(serverResponseCode == 200){

                            runOnUiThread(new Runnable() {
                                public void run() {
                                    Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                        //close the streams //
                        fileInputStream.close();
                        dos.flush();
                        dos.close();

                    } catch (MalformedURLException ex) {

                        ex.printStackTrace();

                        runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                            }
                        });

                        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
                    } catch (Exception e) {

                        e.printStackTrace();

                        runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                            }
                        });
                        Log.e("Upload Exception", "Exception : "  + e.getMessage(), e);
                    }
                    return "serverResponseCode";

                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getApplicationContext(), "file uploaded",
                    Toast.LENGTH_LONG).show();
        }

    }