图像没有从android上传到服务器

时间:2018-02-06 12:32:59

标签: php android

我是android的新手,试图将图像从android上传到服务器。 下面是代码。总是从PHP获取失败消息。

imageupload.php

$type1 = $_REQUEST['type']  ;
    $now = date("Y-m-d h:i:s");
    if($type1 == "Exhibition"){
        $type = 1;
    }
    if($type1 == "Wedding"){
        $type = 2;
    }
    if($type1 == "Culture"){
        $type = 3;
    }
    if($type1 == "Corporate"){
        $type = 4;
    }
    if($type1 == "Sports"){
        $type = 5;
    }
    if($type1 == "Others"){
        $type = 6;
    }

        echo $img_file=$_FILES['image_file']['name'];
        $img_ext=substr($img_file,-4);
        $img_folder="include/img/";
        $img_path=$img_folder.rand(10000,990000).$img_ext;
        $img_type=pathinfo($img_file,PATHINFO_EXTENSION);
            if((move_uploaded_file($_FILES["image_file"]["tmp_name"],$img_path)))
            {
                $jsonarray = array('result'=>'success','msg'=>'Event Added Successfully');      
                }else{
                    $jsonarray = array('result'=>'fail','msg'=>'Something went wrong');
                    echo $myJSON = json_encode($jsonarray);
                }
            }
        else
        {
            $jsonarray = array('result'=>'fail','msg'=>'Failed To Add Event');
            echo $myJSON = json_encode($jsonarray);
        }

UpcomingEvents.java

public class UpcomingEvents extends AppCompatActivity  {
Spinner spinner;
String type;
String[] SPINNERVALUES = {"Exhibition","Wedding","Culture","Corporate","Sports","Others"};
ImageView image;
Button choose, upload;
int PICK_IMAGE_REQUEST = 111;
String URL ="http://10.0.2.2/productioneventapi/imageupload.php";
Bitmap bitmap;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_upcoming_events);

  spinner =(Spinner)findViewById(R.id.spinner);
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(UpcomingEvents.this, android.R.layout.simple_list_item_1, SPINNERVALUES);
  spinner.setAdapter(adapter);
  spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view,
                               int position, long id) {
      type = parent.getItemAtPosition(position).toString();
    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
      // TODO Auto-generated method stub
    }
  });
  image = (ImageView)findViewById(R.id.image);
  choose = (Button)findViewById(R.id.imageupload);
  upload = (Button) findViewById(R.id.addevent);
  choose.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      Intent intent = new Intent();
      intent.setType("image/*");
      intent.setAction(Intent.ACTION_PICK);
      startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
    }
  });
  upload.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      progressDialog = new ProgressDialog(UpcomingEvents.this);
      progressDialog.setMessage("Uploading, please wait...");
      progressDialog.show();

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
      byte[] imageBytes = baos.toByteArray();
      final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

      StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>(){
        @Override
        public void onResponse(String s) {
          progressDialog.dismiss();
          try {
            JSONObject jsonObject = new JSONObject(s);
            String code = jsonObject.getString("msg");
            if (code.equals("success")) {
              Toast.makeText(UpcomingEvents.this,jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
            }else {
              Toast.makeText(UpcomingEvents.this,jsonObject.getString("msg"), Toast.LENGTH_LONG).show();
            }
          }catch (JSONException e) {
            e.printStackTrace();
            Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+s);
          }
        }
      },new Response.ErrorListener(){
        @Override
        public void onErrorResponse(VolleyError volleyError) {
          Toast.makeText(UpcomingEvents.this, "Some error occurred -> "+volleyError, Toast.LENGTH_LONG).show();;
        }
      }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
          Map<String, String> parameters = new HashMap<String, String>();
          parameters.put("image_file", imageString);
          parameters.put("type",type);
          return parameters;
        }
      };

      RequestQueue rQueue = Volley.newRequestQueue(UpcomingEvents.this);
      rQueue.add(request);
    }
  });
}

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
      Uri filePath = data.getData();

      try {
        bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        image.setImageBitmap(bitmap);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

} 在android映像中编码为base64,如何在php中解码? 我试过用 $ imageData = base64_decode($ _ REQUEST ['image_file']);     $ img_file = $的imageData; 这也行不通, 我的方式是不是错了? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

parameters.put("image_file", imageString); 

如果您这样做,那么您将在参数中发送base64编码的文件。

您的php脚本希望您发送文件。如果您保留Volley代码,那么您可以使用

获取base64字符串
$imageString = $_REQUEST['image_file'];

您的move_uploaded_file()现在无法使用。

但是$imageData = base64_decode($_REQUEST['image_file']);应该有效。您只需将数据保存到文件中即可。