使用凌空发送上传图片android没有问题,但问题出现在第一张图片上传i点击上传按钮时,相同的图片将再次上传,即使没有选择但仍然发送以前的图像。如果选择第一张图片上传并选择其他图片上传则没有问题。
使用volley和mysingleton发送数据。
这是ImageUpload.java
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class ImageUpload extends AppCompatActivity implements View.OnClickListener{
private static final String IMAGE_DIRECTORY = "/demonuts";
private Button buttonUpload, buttonChoose;
private ImageView imageView;
private Bitmap bitmap;
private final int GALLERY = 1, CAMERA = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_upload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.buttonChoose:
showPictureDialog();
break;
case R.id.buttonUpload:
uploadImage();
break;
}
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY && resultCode == RESULT_OK) {
if (data != null) {
Uri path = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), path);
imageView.setImageBitmap(bitmap);
imageView.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(ImageUpload.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA && resultCode == RESULT_OK) {
bitmap = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(bitmap);
saveImage(bitmap);
imageView.setVisibility(View.VISIBLE);
Toast.makeText(ImageUpload.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
private void uploadImage(){
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_UPLOAD,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("message");
Toast.makeText(ImageUpload.this,Response,Toast.LENGTH_LONG).show();
imageView.setImageResource(0);
imageView.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("image",imageToString(bitmap));
return params;
}
};
MySingleton.getInstance(ImageUpload.this).addToRequestQueue(stringRequest);
}
private String imageToString(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
byte[] imgBytes = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgBytes,Base64.DEFAULT);
}
}
这是用于检索帖子图像的php文件,仅用于测试使用随机名称。
$response = array();
$name = rand(1,10);
$uploadpath = "../upload/$name.jpg";
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(empty($_POST['image'])){
$response['error'] = true;
$response['message'] = "Please choose images";
}else{
$image = $_POST['image'];
file_put_contents($uploadpath, base64_decode($image));
$response['error'] = false;
$response['message'] = "Image upload succesfully";
}
}else{
$response['error'] = true;
$response['message'] = "Please choose images";
}
echo json_encode($response);
答案 0 :(得分:1)
用这个替换你的方法
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("image",imageToString(bitmap));
bitmap=null;
return params;
}
&安培;上传前检查
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.buttonChoose:
showPictureDialog();
break;
case R.id.buttonUpload:
if(bitmap!=null)
uploadImage();
else
Toast.makeText(this, "add image first", Toast.LENGTH_SHORT).show();
break;
}
}