我正在制作一个注册页面,其中一个放置一个电子邮件地址,一个密码并拍照。我需要通过POST请求将这3个参数发送到服务器。图像的数据类型应该是什么?文件,OutputStrem?或者是其他东西?
我也遇到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
我错过了什么?也许我必须制作一个目录?
这是我的代码:
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();
}
}
}
答案 0 :(得分:1)
您应该将文件/图像编码为base64字符串,如下所示
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);
然后对您的服务器执行POST。 base64解码应该在你的服务器端完成。
您可以为Async http calls
使用 async-http-client 库或 OkHttp
此信息可在此处获取:
所有的归属都应该用于 xil3 ,这是作者。
希望它有所帮助。