简体   繁体   中英

Multipart entity multiple image not sending

In my app I am trying to send multiple images to server..for that I follow this example http://www.mayanklangalia.blogspot.in/2014/04/how-to-upload-multiple-images-on-php.html

Following is my code,when i run app image not submitting to server,and in logcat response

 public class MainActivity extends Activity {
private Button upload, pick;
private ProgressDialog dialog;
MultipartEntity entity;
GridView gv;
int count = 0;
public ArrayList<String> map = new ArrayList<String>();
Bundle b;
TextView noImage;
private ArrayList<String> ImgData;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    b = getIntent().getExtras();
    noImage = (TextView) findViewById(R.id.noImage);
    upload = (Button) findViewById(R.id.btnUpload);
    pick = (Button) findViewById(R.id.btnPicture);
    gv = (GridView) findViewById(R.id.gridview);
    gv.setAdapter(new ImageAdapter(this));
    if (b != null) {
        ImgData = b.getStringArrayList("IMAGE");
        for (int i = 0; i < ImgData.size(); i++) {
            map.add(ImgData.get(i).toString());
        }
    } else {
        noImage.setVisibility(View.VISIBLE);
    }
    upload.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            new ImageUploadTask()
                    .execute(count + "", "pk" + count + ".jpg");
        }
    });
    pick.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Intent i3 = new Intent(MainActivity.this, UploadActivity.class);
            startActivity(i3);
        }
    });
}

class ImageUploadTask extends AsyncTask<String, Void, String> {
    String sResponse = null;
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        dialog = ProgressDialog.show(MainActivity.this, "Uploading",
                "Please wait...", true);
        dialog.show();
    }

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

            String url = "http://mywebsite/web-service/addproduct.php?action=addproduct&name=earringss&categoryid=1&skucode=rings23&sale_rate=345&purchase_rate=45&weight=5&weighttype=kg&description=hellohihihih;

            //URLEncoder.encode("image","UTF-8");
            int i = Integer.parseInt(params[0]);
            Bitmap bitmap = decodeFile(map.get(i));
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            entity = new MultipartEntity();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            //entity.addPart("user_id", new StringBody("199"));
            //entity.addPart("club_id", new StringBody("10"));
            entity.addPart("image", new ByteArrayBody(data,
                    "image/jpeg", params[1]));

            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost,
                    localContext);
            sResponse = EntityUtils.getContentCharSet(response.getEntity());

            System.out.println("sResponse : " + sResponse);
        } catch (Exception e) {
            if (dialog.isShowing())
                dialog.dismiss();
            Log.e(e.getClass().getName(), e.getMessage(), e);

        }
        return sResponse;
    }
    @Override
    protected void onPostExecute(String sResponse) {
        try {
            if (dialog.isShowing())
                dialog.dismiss();
            if (sResponse != null) {
                Toast.makeText(getApplicationContext(),
                        sResponse + " Photo uploaded successfully",
                        Toast.LENGTH_SHORT).show();
                count++;
                if (count < map.size()) {
                    new ImageUploadTask().execute(count + "", "hm" + count
                            + ".jpg");
                }
            }

        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(),
                    Toast.LENGTH_LONG).show();
            Log.e(e.getClass().getName(), e.getMessage(), e);
        }

    }
}

public Bitmap decodeFile(String filePath) {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, o);
    // The new size we want to scale to
    final int REQUIRED_SIZE = 1024;
    // Find the correct scale value. It should be the power of 2.
    int width_tmp = o.outWidth, height_tmp = o.outHeight;
    int scale = 1;
    while (true) {
        if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
            break;
        width_tmp /= 2;
        height_tmp /= 2;
        scale *= 2;
    }
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
    return bitmap;
}

private class ImageAdapter extends BaseAdapter {
    private Context mContext;

    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return map.size();
    }

    public Object getItem(int position) {
        return null;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) { // if it's not recycled, initialize some
                                    // attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85,
                    Gravity.CENTER));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setPadding(1, 1, 1, 1);

        } else {
            imageView = (ImageView) convertView;
        }

        imageView
                .setImageBitmap(BitmapFactory.decodeFile(map.get(position)));
        return imageView;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }
}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    MainActivity.this.finish();
}

I think you need to change your onClick listener or AsynkTask to upload multiple images. Simply, move the logic in doInBackground() to a separate method with image name parameter.

private String uploadImage(String image){ 
    //The existing doInBackground logic
    //Bitmap bitmap = decodeFile(image);
} 
protected String doInBackground(String... params) { 
    for (String s : map){ 
       uploadeImage(s); 
    } 
}

But I think there would be alternative ways to do this such as multi-thread handling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM