多部分实体多图像不发送

时间:2015-04-20 10:46:45

标签: android json http multipartentity

在我的应用中,我正在尝试将多个图像发送到服务器...因为我遵循此示例http://www.mayanklangalia.blogspot.in/2014/04/how-to-upload-multiple-images-on-php.html

以下是我的代码,当我运行app image而不是提交给服务器时,以及logcat响应

 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();
}

1 个答案:

答案 0 :(得分:0)

我认为您需要更改onClick侦听器或AsynkTask以上载多个图像。简单地说,将doInBackground()中的逻辑移动到带有图像名称参数的单独方法。

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

但我认为还有其他方法可以做到这一点,例如多线程处理。