Android 如何将图像发送到服务器

Android 如何将图像发送到服务器,android,image,post,logcat,Android,Image,Post,Logcat,我正在制作一个注册页面,在那里你可以输入电子邮件地址、密码并拍照。我需要通过POST请求将这3个参数发送到服务器。图像的数据类型应该是什么?文件,输出列表?还是别的什么 我还收到一个System.err错误。说: 01-28 13:52:19.214: I/RegisterActivity(27106): path1 : /storage/emulated/0/MyCameraApp 01-28 13:52:19.221: W/System.err(27106): java.io.Fil

我正在制作一个注册页面,在那里你可以输入电子邮件地址、密码并拍照。我需要通过POST请求将这3个参数发送到服务器。图像的数据类型应该是什么?文件,输出列表?还是别的什么

我还收到一个
System.err
错误。说:

    01-28 13:52:19.214: I/RegisterActivity(27106): path1 : /storage/emulated/0/MyCameraApp
01-28 13:52:19.221: W/System.err(27106): java.io.FileNotFoundException: /storage/emulated/0/MyCameraApp/1390913539226.jpg: open failed: ENOENT (No such file or directory)
01-28 13:52:19.229: W/System.err(27106):    at libcore.io.IoBridge.open(IoBridge.java:409)
01-28 13:52:19.229: W/System.err(27106):    at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
01-28 13:52:19.229: W/System.err(27106):    at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
01-28 13:52:19.229: W/System.err(27106):    at com.prjma.lovertech.activity.RegisterActivity.onActivityResult(RegisterActivity.java:211)
01-28 13:52:19.229: W/System.err(27106):    at android.app.Activity.dispatchActivityResult(Activity.java:5322)
01-28 13:52:19.229: W/System.err(27106):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
01-28 13:52:19.229: W/System.err(27106):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
01-28 13:52:19.229: W/System.err(27106):    at android.app.ActivityThread.access$1100(ActivityThread.java:141)
01-28 13:52:19.229: W/System.err(27106):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
01-28 13:52:19.229: W/System.err(27106):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-28 13:52:19.229: W/System.err(27106):    at android.os.Looper.loop(Looper.java:137)
01-28 13:52:19.229: W/System.err(27106):    at android.app.ActivityThread.main(ActivityThread.java:5103)
01-28 13:52:19.229: W/System.err(27106):    at java.lang.reflect.Method.invokeNative(Native Method)
01-28 13:52:19.229: W/System.err(27106):    at java.lang.reflect.Method.invoke(Method.java:525)
01-28 13:52:19.229: W/System.err(27106):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-28 13:52:19.229: W/System.err(27106):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-28 13:52:19.229: W/System.err(27106):    at dalvik.system.NativeStart.main(Native Method)
01-28 13:52:19.237: W/System.err(27106): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
01-28 13:52:19.237: W/System.err(27106):    at libcore.io.Posix.open(Native Method)
01-28 13:52:19.237: W/System.err(27106):    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
01-28 13:52:19.237: W/System.err(27106):    at libcore.io.IoBridge.open(IoBridge.java:393)
01-28 13:52:19.237: W/System.err(27106):    ... 16 more
01-28 13:52:19.214:I/RegisterActivity(27106):路径1:/storage/emulated/0/MyCameraApp
01-28 13:52:19.221:W/System.err(27106):java.io.FileNotFoundException:/storage/emulated/0/MyCameraApp/1390913539226.jpg:open failed:enoint(没有这样的文件或目录)
01-28 13:52:19.229:W/System.err(27106):位于libcore.io.IoBridge.open(IoBridge.java:409)
01-28 13:52:19.229:W/System.err(27106):位于java.io.FileOutputStream。(FileOutputStream.java:88)
01-28 13:52:19.229:W/System.err(27106):位于java.io.FileOutputStream。(FileOutputStream.java:73)
01-28 13:52:19.229:W/System.err(27106):位于com.prjma.lovertech.activity.RegisterActivity.onActivityResult(RegisterActivity.java:211)
01-28 13:52:19.229:W/System.err(27106):在android.app.Activity.dispatchActivityResult(Activity.java:5322)
01-28 13:52:19.229:W/System.err(27106):在android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
01-28 13:52:19.229:W/System.err(27106):在android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)上
01-28 13:52:19.229:W/System.err(27106):在android.app.ActivityThread.access$1100(ActivityThread.java:141)
01-28 13:52:19.229:W/System.err(27106):在android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
01-28 13:52:19.229:W/System.err(27106):位于android.os.Handler.dispatchMessage(Handler.java:99)
01-28 13:52:19.229:W/System.err(27106):在android.os.Looper.loop(Looper.java:137)上
01-28 13:52:19.229:W/System.err(27106):位于android.app.ActivityThread.main(ActivityThread.java:5103)
01-28 13:52:19.229:W/System.err(27106):位于java.lang.reflect.Method.invokenactive(本机方法)
01-28 13:52:19.229:W/System.err(27106):位于java.lang.reflect.Method.invoke(Method.java:525)
01-28 13:52:19.229:W/System.err(27106):位于com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-28 13:52:19.229:W/System.err(27106):位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-28 13:52:19.229:W/System.err(27106):在dalvik.System.NativeStart.main(本机方法)
01-28 13:52:19.237:W/System.err(27106):原因:libcore.io.ErrnoException:open失败:enoint(没有这样的文件或目录)
01-28 13:52:19.237:W/System.err(27106):位于libcore.io.Posix.open(本机方法)
01-28 13:52:19.237:W/System.err(27106):位于libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
01-28 13:52:19.237:W/System.err(27106):位于libcore.io.IoBridge.open(IoBridge.java:393)
01-28 13:52:19.237:W/系统错误(27106):。。。还有16个
我错过了什么?也许我得做个目录

这是我的密码:

public class RegisterActivity extends Activity {

    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final int REQUEST_CAMERA = 1;
    private static final int SELECT_FILE = 2;
    private static final String TAG = "RegisterActivity";

    private ImageView ivAddPhoto;
    private TextView tvAddPhoto;
    private EditText etUserName, etPassword, etEmail;
    private Button btnSubscriptionButton, btnAddPhoto;
    public ProgressDialog pd;

    private Uri fileUri;
    private BackgroundTask mBackgroundTask = null;  

    private String login;
    private String password;
    private String email;
    //private String image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        ivAddPhoto = (ImageView) findViewById(R.id.ivAddPhoto);
        tvAddPhoto = (TextView) findViewById(R.id.tvAddPhoto);
        btnAddPhoto = (Button) findViewById(R.id.btnAddPhoto);
        btnAddPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // start the image capture Intent
                selectImage();
            }
        });

        /*
        final Animation resizeEditTextAnimation = AnimationUtils.loadAnimation(this, R.anim.button_resize_animation);
        resizeEditTextAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {}

            @Override
            public void onAnimationEnd(Animation animation) {
                //...
            }

            @Override
            public void onAnimationRepeat(Animation animation) {}
        });

        final EditText editText = (EditText) findViewById(R.id.ConfirmPassword);

        editText.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus) {
                    editText.startAnimation(resizeEditTextAnimation);
                }
            }
        });
        */

        etUserName = (EditText) findViewById(R.id.etUserName);
        etPassword = (EditText) findViewById(R.id.etPassword);
        etEmail = (EditText) findViewById(R.id.etEmail);

        btnSubscriptionButton = (Button) findViewById(R.id.btnSubscriptionButton);
        btnSubscriptionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login = etUserName.getText().toString();
                password = etPassword.getText().toString();
                email = etEmail.getText().toString();
                //String image = "";

                Log.d(TAG, "login" + login);
                Log.d(TAG, "password" + password);
                Log.d(TAG, "email" + email);

                attemptRegistration();
            }
        });
    }

    private void selectImage() {
        final CharSequence[] items = { "Usa Camera", "Prendi da Galleria", "Chiudi" };

        AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
        builder.setTitle("Aggiungi Foto!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Usa Camera")) {

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));

                    startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);

                } else if (items[item].equals("Prendi da Galleria")) {
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"), SELECT_FILE);
                } else if (items[item].equals("Chiudi")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    /**
     * Rotate image to 90 degrees.
     */
    public Bitmap rotateImage(Bitmap bMap){
        Matrix matrix;        
        //Create object of new Matrix.
        matrix = new Matrix();
        //set image rotation value to 90 degrees in matrix.
        matrix.postRotate(-90);
        //Create bitmap with new values.
        Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0, bMap.getWidth(), bMap.getHeight(), matrix, true);
        return bMapRotate;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {
                File f = new File(Environment.getExternalStorageDirectory().toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bm;
                    BitmapFactory.Options btmapOptions = new BitmapFactory.Options();

                    bm = BitmapFactory.decodeFile(f.getAbsolutePath(),btmapOptions);

                    bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
                    ivAddPhoto.setImageBitmap(bm);
                    tvAddPhoto.setText("Cambia");

                    String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "MyCameraApp";
                    String path2 = Environment.getExternalStorageDirectory() + File.separator + "default";
                    Log.i(TAG, "path1: " + path);
                    Log.i(TAG, "path2: " + path2);
                    f.delete();
                    OutputStream fOut = null;
                    File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                    try {
                        fOut = new FileOutputStream(file);
                        bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                        fOut.flush();
                        fOut.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == SELECT_FILE) {

                Uri selectedImage = data.getData();
                String[] filePath = { MediaStore.Images.Media.DATA };
                Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                Bitmap bm = (BitmapFactory.decodeFile(picturePath));
                bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
                tvAddPhoto.setText("Cambia");
                Log.i("path of image from gallery......******************.........", picturePath+"");
                ivAddPhoto.setImageBitmap(bm);
            }
        }
    }

    /**
     * Here we store the file url as it will be null after returning from camera
     * app
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // save file url in bundle as it will be null on scren orientation changes
        outState.putParcelable("file_uri", fileUri);
    }

    /*
     * Here we restore the fileUri again
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // get the file url   
        fileUri = savedInstanceState.getParcelable("file_uri");
    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptRegistration() {
        if (mBackgroundTask != null) {
            return;
        }

        // Reset errors.
        etUserName.setError(null);
        etPassword.setError(null);
        etEmail.setError(null);

        // Store values at the time of the login attempt.
        login = etUserName.getText().toString();
        email = etEmail.getText().toString();
        password = etPassword.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid userName.
        if (TextUtils.isEmpty(login)) {
            etUserName.setError(getString(R.string.error_field_required));
            focusView = etUserName;
            cancel = true;
        } else if (login.length() < 4) {
            etUserName.setError(getString(R.string.error_invalid_username));
            focusView = etUserName;
            cancel = true;
        }

        // Check for a valid password.
        if (TextUtils.isEmpty(password)) {
            etPassword.setError(getString(R.string.error_field_required));
            focusView = etPassword;
            cancel = true;
        } else if (password.length() < 4) {
            etPassword.setError(getString(R.string.error_invalid_password));
            focusView = etPassword;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            etEmail.setError(getString(R.string.error_field_required));
            focusView = etEmail;
            cancel = true;
        } else if (!email.contains("@")) {
            etEmail.setError(getString(R.string.error_invalid_email));
            focusView = etEmail;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            Log.i(TAG, "ok launch BackgroundTask");

            pd = new ProgressDialog(this);
            pd.show();
            mBackgroundTask = new BackgroundTask();
            mBackgroundTask.execute((Void) null);

        }
    }


    /**
     * Represents an asynchronous task used to upload 
     * information to the webserver and display the results
     */
    public class BackgroundTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.

            int responseStatus = MVPFunctions.getInstance().register(login, password, email, image);

            if (responseStatus == 0){
                return true;
            }

            return true;
        }

        @Override
        protected void onPreExecute(){
            /*
             * This is executed on UI thread before doInBackground(). It is
             * the perfect place to show the progress dialog.
             */
        }

        @Override
        protected void onPostExecute(Boolean result) {
            mBackgroundTask = null;
            pd.cancel();

        }

        @Override
        protected void onCancelled() {
            mBackgroundTask = null;
            pd.cancel();
        }
    }

}
公共类注册表活动扩展活动{
私有静态最终整数请求\图像\捕获=1;
专用静态最终int请求\u摄像机=1;
私有静态最终int选择_文件=2;
私有静态最终字符串标记=“RegisterActivity”;
私人ImageView ivAddPhoto;
私人文本视图tvAddPhoto;
私有编辑文本etUserName、etPassword、etEmail;
私人按钮btnSubscriptionButton,btnAddPhoto;
公共发展对话;
私有Uri文件Uri;
private BackgroundTask mBackgroundTask=null;
私有字符串登录;
私有字符串密码;
私人字符串电子邮件;
//私有字符串图像;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u寄存器);
ivAddPhoto=(ImageView)findViewById(R.id.ivAddPhoto);
tvAddPhoto=(TextView)findViewById(R.id.tvAddPhoto);
btnAddPhoto=(按钮)findViewById(R.id.btnAddPhoto);
btnAddPhoto.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//启动图像捕获计划
选择image();
}
});
/*
最终动画resizeEditTextAnimation=AnimationUtils.loadAnimation(这是R.anim.button\u resize\u动画);
resizeEditTextAnimation.setAnimationListener(新建Animation.AnimationListener()){
@凌驾
onAnimationStart(动画){}上的公共无效
@凌驾
onAnimationEnd上的公共无效(动画){
//...
}
@凌驾
公共无效onAnimationRepeat(动画){}
});
final EditText EditText=(EditText)findViewById(R.id.ConfirmPassword);
setOnFocusChangeListener(新的OnFocusChangeListener(){
@凌驾
public void onFocusChange(视图v,布尔hasFocus){
如果(hasFocus){
editText.startAnimation(调整EditTextAnimation的大小);
}
}
});
*/
etUserName=(EditText)findViewById(R.id.etUserName);
etPassword=(EditText)findViewById(R.id.etPassword);
etEmail=(EditText)findViewById(R.id.etEmail);
BTNSSubscriptionButton=(按钮)findViewById(R.id.BTNSSubscriptionButton);
btnsSubscriptionButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
login=etUserName.getText().toString();
password=etPassword.getText().toString();
email=etEmail.getText().toString();
//字符串图像=”;
Log.d(标记“登录”+登录);
日志d(标签“密码”+密码);
日志d(标记“电子邮件”+电子邮件);
尝试注册();
}
});
}
私人无效选择
Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap
object byte[] b = baos.toByteArray();

String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);