1

I am trying to upload images from android to php server The server is working all good for ios using objective c but in android I did not not know how to upload the images. I have tried the below code but the server returns message that (images are not in proper format or missing image file

        ArrayList<File> imageFiles= new ArrayList<File>();
        for(int i=0;i<mCameraDataList.size();i++) {
           File f = new File(getFilesDir(),"image"+i+".jpg");
            f.createNewFile();
            Bitmap bitmap = Bitmap.createScaledBitmap(
                    BitmapFactory.decodeByteArray(mCameraDataList.get(i), 0, mCameraDataList.get(i).length),CommonMethods.getDeviceWidth(this), CommonMethods.getDeviceHeight(this), true);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
            byte[] bitmapdata = stream.toByteArray();
            FileOutputStream fos = new FileOutputStream(f);
            fos.write(bitmapdata);
            fos.flush();
            fos.close();
            imageFiles.add(f);
        }

  public static void postProduct(ArrayList<File> nImages) throws UnsupportedEncodingException {
        MultipartEntityBuilder entity=MultipartEntityBuilder.create();
        entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("authenticity",new StringBody("1"));
        entity.addPart("brand_id",new StringBody("1"));
        entity.addPart("cat_id",new StringBody("2"));
        entity.addPart("color_id1",new StringBody("2"));
        entity.addPart("color_id2",new StringBody("3"));
        entity.addPart("condition_id",new StringBody("3"));
        entity.addPart("description",new StringBody("Bgvv"));
        entity.addPart(Constants.KeyValues.DEVICE_ID,new StringBody(Constants.DEVICE_ID));
        entity.addPart("images",new StringBody("images"));
        entity.addPart("lon",new StringBody("74.344630"));
        entity.addPart("lat",new StringBody("31.516762"));
        entity.addPart("name_brand",new StringBody("2 puffs"));
        entity.addPart("package_size",new StringBody("0"));
        entity.addPart("selling_price", new StringBody("20"));
        entity.addPart("title",new StringBody("My test"));
        entity.addPart(Constants.KeyValues.UID,new StringBody(String.valueOf(CommonObjects.getUserProfile().getUid())));
        for(int i=0;i<nImages.size();i++)
        {
            File f=new File(nImages.get(i).getAbsolutePath());
            if(f.exists()){
                entity.addPart(Constants.KeyValues.IMAGES, new FileBody(f, "image/jpeg"));
            }
        }
        new SetDataToServer(Constants.NetworkServiceMethods.Product.POST_PRODUCT, entity, new SetDataToServer.SetDataNotifier() {
            @Override
            public void onDataReceived(boolean isError, String message, JSONObject jsonObj) {
                ArrayList<String> postProductResult =new ArrayList<String>();
                try {
                    Log.e("JSON",jsonObj.toString());
                    if (!jsonObj.isNull(Constants.KeyValues.DATA)) {
                        JSONObject jsonObjectData = jsonObj.getJSONObject(Constants.KeyValues.DATA);
//                        postProductResult.add(jsonObjectData.getString(Constants.KeyValues.CON_ID));
//                        postProductResult.add(jsonObjectData.getString(Constants.KeyValues.ORDER_ID));
                    }
                } catch (JSONException e) {
                    isError = true;
                    message = "Sorry! Error occurred in data parsing";
                }
                productHandlerMethods.onPostProductResult(isError, message, postProductResult);
            }
        }).callServerToSetData();
    }

Can any body tell what I am doing wrong.

Server side code

public function postproduct_post() {
        $brand_id = $this->post('brand_id');
        if ($brand_id == '') {
            $brand_name = $this->post('name_brand');
            if ($brand_name == '')
                $this->create_error(-1);
            $brand_id = $this->Mproduct->insertBrandName($brand_name);
        } else {
            if (!$this->Mproduct->_checkBrandId($brand_id))
                $this->create_error(-15, 'brand_id');
        }

        $time = time();
        $uid = $this->post('uid');
        $cat_id = $this->post('cat_id');
        $title = $this->post('title');
        $description = $this->post('description');
        $condition_id = $this->post('condition_id');
        $authenticity = $this->post('authenticity');

        $color_id1 = $this->post('color_id1', 0);
        $color_id2 = $this->post('color_id2', 0);

        $selling_price = $this->post('selling_price');
        $package_size = $this->post('package_size');
        $lat = $this->post('lat');
        $lon = $this->post('lon');

        if ($uid == '' || $cat_id == '' || $title == '' || $description == ''
                || $color_id1 == '' || $condition_id == '' || $authenticity == '') {
            $this->create_error(-1);
        }

        if (!$this->Muser->_checkUid($uid)) 
            $this->create_error(-10);

        if (!$this->Mproduct->_checkCatId($cat_id)) 
            $this->create_error(-15, 'cat_id');

        if ($color_id1 > 0 && !$this->Mproduct->_checkColorId($color_id1)) {
            $this->create_error(-15, 'color_id1');
        }

        if ($color_id2 > 0 && !$this->Mproduct->_checkColorId($color_id2)) {
            $this->create_error(-15, 'color_id2');
        }
        $images = isset($_FILES['images']) ? $_FILES['images'] : null;
        if ($images == null || count($images['name']) <= 0) {
            $this->create_error(-21);
        }

        $this->load->model('Mfile');

        if (!$this->Mfile->checkArrayImage($images)) {
            $this->create_error(-13);
        }

        if (!$this->Mproduct->_checkConditionId($condition_id)) {
            $this->create_error(-15, 'condition_id');
        }

        $params = array();
        $params['owner_id'] = $uid;
        $params['cat_id'] = $cat_id;
        $params['title'] = $title;
        $params['added'] = $time;
        $params['brand_id'] = $brand_id;
        $params['description'] = $description;
        $params['is_sell'] = 1;
        $params['size_id'] = 101;
        $params['is_swap'] = 0;
        $params['is_give'] = 0;
        $params['color_id1'] = $color_id1;
        $params['color_id2'] = $color_id2;
        $params['condition_id'] = $condition_id;
        $params['authenticity'] = $authenticity;
        $params['lat'] = $lat;
        $params['lon'] = $lon;
        $params['last_activity'] = $time;
        $params['last_comment'] = '';
        $params['status'] = 1;

        if ($selling_price != '')
            $params['selling_price'] = $selling_price;
        if ($package_size != '')
            $params['package_size'] = $package_size;

        $product_id = $this->Mproduct->insertProduct($params);
        if ($product_id == -1) {
            $this->create_error(-16);
        }

        $paths = $this->Mfile->saveArrayImage($images, $product_id, $time);
        if (count($paths) <= 0) {
            $this->create_error(-13);
        }

        $params = array();
        $params['image'] = $this->Mfile->createThumbProduct($paths[0]);
        $params['status'] = 1;
        $this->Mproduct->updateAfterInsertProduct($product_id, $params);
        $this->Mproduct->upItemInCat($cat_id);
        $this->Mproduct->upItemInBrand($brand_id);
        $this->Muser->upItemOfUser($uid);

        $this->Mproduct->insertProductImage($product_id, $paths);
        //$this->Mfeed->insertNotifyNewProduct($time, $uid, $product_id);
        //$this->Mpush->createNotiAddProduct($uid, $product_id);
        $uids = $this->Mproduct->getUidsFollowUser($uid);
        $this->load->model('Mnotify');
        $this->Mnotify->createNotifyMany($uids, $product_id, $uid, 7, array('product_id' => $product_id, 'uid' => $uid));
        $this->Mfeed->insertFeedWhenSell($time, $product_id);

        $data = array();
        $data['product_id'] = $product_id;
        $this->create_success($data, 'Add success');        
    }
12
  • No. Because you should first tell us in which format the images should be send. Commented Apr 29, 2015 at 17:27
  • File f=new File(nImages.get(i).getAbsolutePath());. You mean: File f = nImages.get(i);. Commented Apr 29, 2015 at 17:28
  • The images are in jpg format as written in the code Commented Apr 29, 2015 at 17:32
  • 1
    server returns message that (images are not in proper format or missing image file. I repeat: Ask the server guys in which format you have to send them. Commented Apr 29, 2015 at 17:34
  • server accpts images in file and format images having jpg type Commented Apr 29, 2015 at 17:35

1 Answer 1

2

Try to upload the image via below service written in android, make sure that image path is correct in below code, place the image in sdcard :

public class MyService extends Service {
    SharedPreferences sharedPref;
    SharedPreferences.Editor editor;
    int serverResponseCode = 0;
    String upLoadServerUri = null;

    private static final String TAG = "com.example.ServiceExample";

    @Override
    public void onCreate() {
        Log.i(TAG, "Service onCreate");
        sharedPref = getSharedPreferences("myfiles", MODE_PRIVATE);
        /************* Php script path ****************/
        upLoadServerUri = "http://myserver/uploadimage.php";

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.i(TAG, "Service onStartCommand " + startId);

        final int currentId = startId;

        Runnable r = new Runnable() {
            public void run() {

                for (int i = 0; i < 3; i++) {
                    // long endTime = System.currentTimeMillis() + 10*1000;

                    // while (System.currentTimeMillis() < endTime) {
                    synchronized (this) {
                        try {

                            uploadFile(sharedPref.getString(i + "", ""));

                        } catch (Exception e) {
                        }

                    }
                    // }
                    Log.i(TAG, "Service running " + currentId);
                }
                stopSelf();
            }
        };

        Thread t = new Thread(r);
        t.start();
        return Service.START_STICKY;
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        Log.i(TAG, "Service onBind");
        return null;
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "Service onDestroy");
    }

    public int uploadFile(String sourceFileUri) {

        String fileName = sourceFileUri;

        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;
        // File sourceFile = new
        // File(Environment.getExternalStorageDirectory(),sourceFileUri);
        File sourceFile = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/" + fileName);
        if (!sourceFile.isFile()) {

            return 0;

        } else {
            try {

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

                // 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=""+ fileName + """
                // + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + fileName + "\"" + 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)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

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

                if (serverResponseCode == 200) {

                }

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

            } catch (MalformedURLException ex) {

                ex.printStackTrace();

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

                e.printStackTrace();

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

            return serverResponseCode;

        } // End else block
    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

I dont think so this would work for my condition as in my code I have to send other info along with image and on server side only images in file form are acceptable
the above code shows only multipart upload of image, you need to add rest of part , yes could send other info via posting to url

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.