Android将图像发送到网络服务器

时间:2014-11-05 12:36:10

标签: android image webserver

我有这个任务将我用我的应用程序拍摄的照片发送到网络服务器。这是我的相机活动,我想在onActivityResult方法中发送图像。我无法找到最新的解决方案,因为我所能找到的似乎都在使用现已弃用的MultipartEntity。

package com.ndjk;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;

public class CameraActivity extends Activity {

private static final int CAMERA_REQUEST = 1888;
public ImageView imageView;
public static final String URI_PATH = "Uri";
Uri imageUri = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_frontpage);
    imageView = (ImageView) findViewById(R.id.pictureImageView);
    open();

}

public void open() {
    Intent cameraIntent = new Intent(
            android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(cameraIntent, CAMERA_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    Bitmap bp = (Bitmap) data.getExtras().get("data");
    imageView.setImageBitmap(bp);

    Intent frontPageIntent = new Intent(this, FrontPageActivity.class);
    imageUri = data.getData();

    frontPageIntent.putExtra(URI_PATH, imageUri.toString());
    frontPageIntent.putExtra("MapPhoto", bp);

    startActivity(frontPageIntent);
    }

    }

3 个答案:

答案 0 :(得分:3)

修改 - 1

您可以使用以下代码打开相机:

    private static final int RESULT_TAKE_PHOTO = 1;
    Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(i, RESULT_TAKE_PHOTO);

您的onActivityResult必须是这样的:

if (resultCode == RESULT_OK) {
            File file = null;
            String filePath = null;
            try {

                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                filePath = cursor.getString(columnIndex);
                cursor.close();

                rotateDegree = getCameraPhotoOrientation(getApplicationContext(), selectedImage, picturePath);
                bmp = BitmapFactory.decodeFile(picturePath);
                bmp = rotateImage(bmp, rotateDegree);

                file = new File(filePath);
                FileOutputStream fOut = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
                fOut.flush();
                fOut.close();
                resultCode=0;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

因此,如果拍照,您可以使用此AsyncTask进行发送。您可以在将文件发送到服务器时显示进度条。它为我工作。

public class SendFile extends AsyncTask<String, Integer, Integer> {

    private Context conT;
    private ProgressDialog dialog;
    private String SendUrl = "";
    private String SendFile = "";
    private String Parameters = "";
    private String result;
    public File file;

    SendFile(Context activity, String url, String filePath, String values) {
        conT = activity;
        dialog = new ProgressDialog(conT);
        SendUrl = url;
        SendFile = filePath;
        Parameters = Values;
    }

    @Override
    protected void onPreExecute() {
        file = new File(SendFile);
        dialog.setMessage("Please Wait..");
        dialog.setCancelable(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMax((int) file.length());
        dialog.show();
    }

    @Override
    protected Integer doInBackground(String... params) {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        InputStream inputStream = null;
        String twoHyphens = "--";
        String boundary = "*****"
                + Long.toString(System.currentTimeMillis()) + "*****";
        String lineEnd = "\r\n";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 512;

        String[] q = SendFile.split("/");
        int idx = q.length - 1;
        try {

            FileInputStream fileInputStream = new FileInputStream(file);

            URL url = new URL(SendUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("User-Agent",
                    "Android Multipart HTTP Client 1.0");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + boundary);

            outputStream = new DataOutputStream(
                    connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream
                    .writeBytes("Content-Disposition: form-data; name=dosya; filename=\""
                            + q[idx] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: image/jpg" + lineEnd);
            outputStream.writeBytes("Content-Transfer-Encoding: binary"
                    + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            int boyut = 0;
            while (bytesRead > 0) {
                boyut += bytesRead;
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                dialog.setProgress(boyut);
            }

            outputStream.writeBytes(lineEnd);

            String[] posts = Bilgiler.split("&");
            int max = posts.length;
            for (int i = 0; i < max; i++) {
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                String[] kv = posts[i].split("=");
                outputStream
                        .writeBytes("Content-Disposition: form-data; name=\""
                                + kv[0] + "\"" + lineEnd);
                outputStream.writeBytes("Content-Type: text/plain"
                        + lineEnd);
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(kv[1]);
                outputStream.writeBytes(lineEnd);
            }

            outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                    + lineEnd);
            inputStream = connection.getInputStream();
            result = this.convertStreamToString(inputStream);
            Log.v("TAG","result:"+result);
            fileInputStream.close();
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {

        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        dialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(Integer result1) {
        dialog.dismiss();
    };

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

如果您要发送到PHP服务器,此代码将帮助您。

<?php 
     $file_path = "test/";
     $username= $_POST["username"];
     $password= $_POST["password"];
     $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
     if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
         echo "success";
     } else{
         echo "fail";
     }

?>

编辑 - 2:

您可以将此AsyncTask称为:

        String FormData = "username=" + Session.getUsername()
                + "&password=" + Session.getPassword() ;
        SendFile SendIt= new SendFile(this, upLoadServerUri, filePath,FormData);
        SendIt.execute();

答案 1 :(得分:2)

作为替代方案,我强烈建议使用来自Square的Retrofit REST库。 Retrofit

您将创建一个这样的Java接口:

@Multipart
@POST("/webservice/{userid}/avatar.json")
Object uploadImage(
        @Header("Rest-User-Token") String token,
        @Path("userid") String userId,
        @Part("FileData") TypedFile pictureFile

);

然后,只是将Intent数据转换为File对象,而不是按如下方式创建TypedFile:

TypedFile in = new TypedFile("image/jpeg", imageFile);

答案 2 :(得分:1)

我认为答案在这里: https://stackoverflow.com/a/19196621/1652236

您应该使用MultipartEntityBuilder作为替代