如何使用multipart实体将图像上传到服务器?

时间:2014-12-20 10:57:54

标签: android json image-uploading

我正在创建一个应用程序,在我的应用程序中,我添加了一个选项来浏览库中的图像,然后上传到服务器,我之前问过这个问题,但没有得到好的答案,而且为了上传图像,我正在按照本教程{{ 3}}及以下我发布我的代码可以任何人帮助我..

enter image description here enter image description here enter image description here

public class PhotoUpload extends Activity{
private Button upload, pick;
private ProgressDialog dialog;
MultipartEntity entity;
GridView gv;
int count = 0;
String matchId;
ArrayList<String> ImgData;
public ArrayList<String> map = new ArrayList<String>();
Bundle b;
TextView noImage;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photos_upload);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);

    b = getIntent().getExtras();

    matchId=this.getIntent().getStringExtra("id");
    System.out.println(matchId);
    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(PhotoUpload.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(PhotoUpload.this, "Uploading",
                "Please wait...", true);
        dialog.show();
    }

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

            String url = "http://mnbmnbnmb.com/webservice/addphoto?version=apps&user_login_id="+matchId+"&image_1="+ImgData+"&action=save";
            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_login_id", new StringBody("199"));
            entity.addPart("image_1", new StringBody("10"));
            entity.addPart("action", 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();
    PhotoUpload.this.finish();  
}
}

UploadActivity.java

public class UploadActivity extends Activity{

private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
private static final int PICK_FROM_CAMERA = 1;
ArrayList<String> IPath = new ArrayList<String>();
public static Uri uri;

/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);

    final String[] columns = { MediaStore.Images.Media.DATA,
            MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    Cursor imagecursor = managedQuery(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, orderBy);
    int image_column_index = imagecursor
            .getColumnIndex(MediaStore.Images.Media._ID);
    this.count = imagecursor.getCount();
    this.thumbnails = new Bitmap[this.count];
    this.arrPath = new String[this.count];
    this.thumbnailsselection = new boolean[this.count];
    for (int i = 0; i < this.count; i++) {
        imagecursor.moveToPosition(i);
        int id = imagecursor.getInt(image_column_index);
        int dataColumnIndex = imagecursor
                .getColumnIndex(MediaStore.Images.Media.DATA);
        thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
                getApplicationContext().getContentResolver(), id,
                MediaStore.Images.Thumbnails.MICRO_KIND, null);
        arrPath[i] = imagecursor.getString(dataColumnIndex);
    }
    GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imageAdapter = new ImageAdapter();
    imagegrid.setAdapter(imageAdapter);
    imagecursor.close();



    final Button uploadBtn = (Button) findViewById(R.id.uploadDONE);
    uploadBtn.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            final int len = thumbnailsselection.length;
            int cnt = 0;
            String selectImages = "";
            for (int i = 0; i < len; i++) {
                if (thumbnailsselection[i]) {
                    cnt++;
                    selectImages = arrPath[i];
                    IPath.add(selectImages);
                }
            }

            if (cnt == 0) {
                Toast.makeText(getApplicationContext(),
                        "Please select at least one image",
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(),
                        "You've selected Total " + cnt + " image(s).",
                        Toast.LENGTH_LONG).show();
                Log.d("SelectedImages", selectImages);



                Intent intentMessage = new Intent(UploadActivity.this,
                        PhotoUpload.class);
                intentMessage.putStringArrayListExtra("IMAGE", IPath);
                startActivity(intentMessage);
            }
        }
    });
}

public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public ImageAdapter() {
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return count;
    }

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

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.galleryitem, null);
            holder.imageview = (ImageView) convertView
                    .findViewById(R.id.thumbImage);
            holder.checkbox = (CheckBox) convertView
                    .findViewById(R.id.itemCheckBox);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.checkbox.setId(position);
        holder.imageview.setId(position);
        holder.checkbox.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                CheckBox cb = (CheckBox) v;
                int id = cb.getId();
                if (thumbnailsselection[id]) {
                    cb.setChecked(false);
                    thumbnailsselection[id] = false;
                } else {
                    cb.setChecked(true);
                    thumbnailsselection[id] = true;
                }
            }
        });



        holder.imageview.setImageBitmap(thumbnails[position]);
        holder.checkbox.setChecked(thumbnailsselection[position]);
        holder.id = position;
        return convertView;
    }
}

class ViewHolder {
    ImageView imageview;
    CheckBox checkbox;
    int id;
}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    Intent i = new Intent(UploadActivity.this, MainActivity.class);
    UploadActivity.this.finish();
    startActivity(i);
    super.onBackPressed();
}

}

4 个答案:

答案 0 :(得分:1)

我正在使用此代码将文件上传到服务器:(如果我理解你的问题)

首先选择文件
在你的选择imge btn监听器中运行这个方法之一:

从图库中选择照片:

 void startImagePicker() {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_SEND_IMAGE); 
        }

用相机拍照:

void startPhotoTaker() {

        // create Intent to take a picture and return control to the calling application
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File photo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "cs_" + new Date().getTime() + ".jpg");
        mLastPhoto = Uri.fromFile(photo);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                mLastPhoto);

        // start the image capture Intent
        startActivityForResult(intent, REQUEST_TAKE_PICTURE);
    }

从文件管理器中选择任何文件:

void startFilePicker() {
        Intent selectFile = new Intent(Intent.ACTION_GET_CONTENT);
        selectFile.setType("file/*");
        Intent intentChooser = Intent.createChooser(selectFile, "Select File");

        if (intentChooser != null)
            startActivityForResult(Intent.createChooser(selectFile, "Select File"), REQUEST_SEND_FILE);
    }
你的onActivityForResault方法中的

复制了这个:

onActivityResualt中的

if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_SEND_IMAGE) {
                Uri uri = resultIntent.getData();
                if (uri == null) {
                    return;
                }
                File file = new File(getRealPathFromURI(uri));
                final Handler handler = new Handler();
                MediaScannerConnection.scanFile(
                        this, new String[]{file.toString()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, final Uri uri) {

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadFile(uri);
                                    }
                                });
                            }
                        });
            } else if (requestCode == REQUEST_SEND_FILE |) {
                Uri uri = resultIntent.getData();
                if (uri == null) {
                    return;
                }

                uploadFile(uri);
            } else if (requestCode == REQUEST_TAKE_PICTURE) {

                File file = new File(getRealPathFromURI(mLastPhoto));
                final Handler handler = new Handler();
                MediaScannerConnection.scanFile(
                        this, new String[]{file.toString()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            public void onScanCompleted(String path, final Uri uri) {

                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadFile(mLastPhoto);
                                    }
                                });
                            }
                        });

            } 
        }

将文件上传到服务器:

private String uploadFile(Uri resourceUri) {
        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;
        final File sourceFile = new File(getRealPathFromURI(resourceUri));
        String serverResponseMessage = null;
        String responce = null;
        if (!sourceFile.isFile()) {

            dialog.dismiss();

            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(), "File not found !", Toast.LENGTH_LONG).show();
                }
            });

            return "no file";
        } else {
            try {
                FileInputStream fileInputStream = new FileInputStream(sourceFile.getPath());
                URL url = new URL("your upload server/API 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(POST_FIELD, sourceFile.getName());
                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"" + POST_FIELD + "\";filename="
                        + sourceFile.getName() + lineEnd);
                dos.writeBytes(lineEnd);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                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);

                }
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                int serverResponseCode = conn.getResponseCode();
                serverResponseMessage = conn.getResponseMessage();
                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);
                if (serverResponseCode <= 200) {

                    runOnUiThread(new Runnable() {
                        public void run() {

                            Toast.makeText(PreviewActivity.this, "File Upload Complete.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                fileInputStream.close();
                dos.flush();
                dos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (MalformedURLException ex) {
                dialog.dismiss();
                ex.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {

                        Toast.makeText(PreviewActivity.this, "MalformedURLException",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (IOException e) {
                dialog.dismiss();
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(PreviewActivity.this, "Got Exception : see logcat ",
                                Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception", "Exception : "
                        + e.getMessage(), e);
            }
        }
        dialog.dismiss();
        return responce;
    }  

答案 1 :(得分:1)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
    filePath = data.getData();
    try {
        bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        pro.setImageBitmap(bitmap);
        updatepro();

    } catch (IOException e) {
        e.printStackTrace();
    }
}
}
  VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<NetworkResponse>() {
                @Override
                public void onResponse(NetworkResponse response) {
                    Log.d("Response", String.valueOf(response));
                    try {
                        JSONObject obj = new JSONObject(new String(response.data));

                        Toast.makeText(getApplicationContext(),"success", Toast.LENGTH_SHORT).show();


                    } catch (JSONException e) {

                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }) {

        /*
        * If you want to add more parameters with the image
        * you can do it here
        * here we have only one parameter with the image
        * which is tags
        * */
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("aid", aid);
            return params;
        }

        /*
        * Here we are passing image by renaming it with a unique name
        * */
        @Override
        protected Map<String, DataPart> getByteData() {
            Map<String, DataPart> params = new HashMap<>();
            long imagename = System.currentTimeMillis();///IMAGE NAME SETTING DURING
            params.put("img1", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
            return params;

        }

    };

    //adding the request to volley
    Volley.newRequestQueue(this).add(volleyMultipartRequest);

答案 2 :(得分:0)

您可以使用Volley(来自Google的库)来处理您的网络请求。 而且,如果您使用Volley,还可以使用附加组件来处理Multipart Request。 像VolleyExMultiPartRequest.java

答案 3 :(得分:0)

已经很晚了,但可能会帮助别人

这是将图像文件作为多部分发送到服务器的完整代码

private void UploadImagep(Uri ur){

    File sourceFile = new File(ur.getPath());


    try {
        final com.squareup.okhttp.MediaType MEDIA_TYPE_PNG = com.squareup.okhttp.MediaType.parse("image/*");

        com.squareup.okhttp.RequestBody requestBody = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addFormDataPart("image", "image.png", com.squareup.okhttp.RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
                .build();

        com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
                .url("url")
                .put(requestBody)
                .addHeader("Authorization", "Token " + auth)
                .addHeader("Content-Type", "application/x-www-formurlencoded")

                .build();

        OkHttpClient client = new OkHttpClient();
        com.squareup.okhttp.Response response = client.newCall(request).execute();

        if (response.isSuccessful() == true) {
            super.recreate();
        } else {

        }


        System.out.println("Response data " + response);

    } catch (Exception e) {

        System.out.println("Response error is" + e);

    }


}