android图像由多部门上传到服务器

时间:2014-11-06 08:58:43

标签: android server multipartentity

我写了一个代码,它从Android设备拍照,然后将其上传到服务器上。还可以从图库上传图片。从画廊上传工作完美。当点击捕获按钮时它能够用于移动相机,但是当我返回时我没有获得任何图像,当我检查图库时没有捕获图像。

还有明确的许可

android.permission.WRITE_EXTERNAL_STORAGE"
android.permission.READ_EXTERNAL_STORAGE"
android.permission.CAMERA"

这是我的片段onCreateView()类中的代码:

mTakePhoto = (Button)  rootView.findViewById(R.id.take_photo);
        mselectPhoto = (Button)  rootView.findViewById(R.id.select_photo);
        mImageView = (ImageView)  rootView.findViewById(R.id.imageview);

        mTakePhoto.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            Intent intent = new Intent(
                    MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,
                    TAKE_PICTURE);
        }
    });

    mselectPhoto.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(i,
                    IMAGE_PICKER_SELECT);
        }
    });

在上面的代码中,我认为意图完美无缺

在下面的代码中,(requestCode == IMAGE_PICKER_SELECT)条件完美无缺。但是当我拍摄PICTURE时似乎没有得到任何数据

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == IMAGE_PICKER_SELECT
            && resultCode == Activity.RESULT_OK) {
        Bitmap bitmap = getBitmapFromCameraData(data, getActivity());
        int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
        Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
        mImageView.setImageBitmap(scaled);
        new UploadTask().execute(bitmap);
    }
    if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK
            && data != null) {
        // get bundle
        Bundle extras = data.getExtras();
        // get bitmap
        cameraBitmap = (Bitmap) extras.get("data");
        int nh = (int) (cameraBitmap.getHeight() * (512.0 / cameraBitmap
                .getWidth()));
        Bitmap scaled = Bitmap.createScaledBitmap(cameraBitmap, 512, nh,
                true);
        mImageView.setImageBitmap(scaled);
        new UploadTask().execute(cameraBitmap);
        // setPic();

    }
}

我还提供了我的Multipartentity类的代码

public class MultipartEntity implements HttpEntity {
enter code here
private String boundary = null;

ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;

public MultipartEntity() {
    this.boundary = System.currentTimeMillis() + "";
}

public void writeFirstBoundaryIfNeeds(){
    if(!isSetFirst){
        try {
            out.write(("--" + boundary + "\r\n").getBytes());
        } catch (final IOException e) {

        }
    }
    isSetFirst = true;
}

public void writeLastBoundaryIfNeeds() {
    if(isSetLast){
        return ;
    }
    try {
        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
    } catch (final IOException e) {

    }
    isSetLast = true;
}

public void addPart(final String key, final String value) {
    writeFirstBoundaryIfNeeds();
    try {
        out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
        out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
        out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
        out.write(value.getBytes());
        out.write(("\r\n--" + boundary + "\r\n").getBytes());
    } catch (final IOException e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());

    }
}

public void addPart(final String key, final String fileName, final InputStream fin){
    addPart(key, fileName, fin, "application/octet-stream");
}

public void addPart(final String key, final String fileName, final InputStream fin, String type){
    writeFirstBoundaryIfNeeds();
    try {
        type = "Content-Type: "+type+"\r\n";
        out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
        out.write(type.getBytes());
        out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());

        final byte[] tmp = new byte[4096];
        int l = 0;
        while ((l = fin.read(tmp)) != -1) {
            out.write(tmp, 0, l);
        }
        out.flush();
    } catch (final IOException e) {

    } finally {
        try {
            fin.close();
        } catch (final IOException e) {

        }
    }
}

public void addPart(final String key, final File value) {
    try {
        addPart(key, value.getName(), new FileInputStream(value));
    } catch (final FileNotFoundException e) {

    }
}

@Override
public long getContentLength() {
    writeLastBoundaryIfNeeds();
    return out.toByteArray().length;
}

@Override
public Header getContentType() {
    return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}

@Override
public boolean isChunked() {
    return false;
}

@Override
public boolean isRepeatable() {
    return false;
}

@Override
public boolean isStreaming() {
    return false;
}

@Override
public void writeTo(final OutputStream outstream) throws IOException {
    outstream.write(out.toByteArray());
}

@Override
public Header getContentEncoding() {
    return null;
}

@Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
    if (isStreaming()) {
        throw new UnsupportedOperationException(
        "Streaming entity does not implement #consumeContent()");
    }
}

@Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
    return new ByteArrayInputStream(out.toByteArray());
}

}

我几乎全力以赴。帮助!

2 个答案:

答案 0 :(得分:0)

使用以下代码打开相机并检查:

private Uri mImageCaptureUri;
mImageCaptureUri = Uri.parse("content://YOUR PACKAGE NAME/");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,mImageCaptureUri);
intent.putExtra("return-data", true);
startActivityForResult(intent,TAKE_PICTURE);

答案 1 :(得分:0)

我创建了一个在单击按钮时调用的方法

        mTakePhoto.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
        takePhoto();
        }
    });

intent和getTempFile()保存临时文件的方法..

    private void takePhoto(){
      final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(getActivity())) ); 
      startActivityForResult(intent, TAKE_PICTURE);
    }

    private File getTempFile(Context context){
      final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
      if(!path.exists()){
        path.mkdir();
      }
      return new File(path, "image.tmp");
    }

此链接可以帮助我 http://www.tutorialforandroid.com/2010/10/take-picture-in-android-with.html