如何通过HTTP从Android发送图像

时间:2019-04-09 19:44:37

标签: php android apache http

我正在构建一个apache2服务器,该服务器从android设备接收图像并将其保存。该服务器位于ubuntu上,并运行一个PHP脚本来保存图像,但似乎不起作用。在apache访问日志中,没有来自设备的访问,因此我想问题出在我编写的应用程序中。 申请代码:

package com.example.t8361423.myclientapplication;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {

    ProgressDialog pDialog;
    String image;


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

        pDialog = new ProgressDialog(this);

        Button btn_upload = (Button) findViewById(R.id.btn_upload);
        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 0);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data != null && requestCode == 0) {


            if (resultCode == RESULT_OK) {
                Uri targetUri = data.getData();
                Bitmap bitmap;
                try {
                    bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
                    Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 500, 500, false);
                    image = ConvertBitmapToString(resizedBitmap);

                    Upload();

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    //method to convert the selected image to base64 encoded string

    public static String ConvertBitmapToString(Bitmap bitmap){
        String encodedImage = "";

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        try {
            encodedImage= URLEncoder.encode(Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return encodedImage;
    }


    private void Upload() {

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                new UploadFile().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "http://35.198.163.40/hello.php");
            } else {
                new UploadFile().execute("http://35.198.163.40/hello.php");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    private class UploadFile extends AsyncTask<String, Void, Void> {


        private String Content;
        private String Error = null;
        String data = "";
        private BufferedReader reader;


        protected void onPreExecute() {

            pDialog.show();

            try {

                data += "&" + URLEncoder.encode("image", "UTF-8") + "=" + "data:image/png;base64," + image;

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }

        protected Void doInBackground(String... urls) {

            HttpURLConnection connection = null;
            try {
                URL url = new URL(urls[0]);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();

                con.setRequestMethod("POST");
                con.setUseCaches(false);
                con.setDoInput(true);
                con.setDoOutput(true);
                con.setRequestProperty("Content-Length", "" + data.getBytes().length);
                con.setRequestProperty("Connection", "Keep-Alive");
                con.setDoOutput(true);

                OutputStream os = con.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

                //make request
                writer.write(data);
                writer.flush();
                writer.close();
                reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }

                Content = sb.toString();
            } catch (Exception ex) {
                Error = ex.getMessage();
            }
            return null;

        }


        protected void onPostExecute(Void unused) {
            // NOTE: You can call UI Element here.

            pDialog.dismiss();
            try {

                if (Content != null) {
                    JSONObject jsonResponse = new JSONObject(Content);
                    String status = jsonResponse.getString("status");
                    if ("200".equals(status)) {

                        Toast.makeText(getApplicationContext(), "File uploaded successfully", Toast.LENGTH_SHORT).show();

                    } else {

                        Toast.makeText(getApplicationContext(), "Something is wrong ! Please try again.", Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}

PHP脚本位于/ var / www / html,这是代码:

<?php
require_once('conn/config.php');//use path and name of your connection file
$base64_string=$_POST['image'];
$image_name = uniqid().".png";

 if(validateString($base64_string))
 {
 $data = explode(',', $base64_string);
 $ifp = fopen($_SERVER['DOCUMENT_ROOT'] ."/images/".$image_name, "wb");// use your folder path
 fwrite($ifp, base64_decode($data[1]));
 fclose($ifp);

//inserting the picture name to your table , here i am just inserting pic name, you can insert
//other details also
 $query = "INSERT INTO your_table(pic) VALUES (?)";
 $stmt = $con->prepare($query);
 $stmt->bind_param("s",$image_name);
 $stmt->execute();
 $id=$stmt->insert_id;

 if($stmt->affected_rows==1){

 $final_arr=array();
 $final_arr["status"] = "200";
 $final_arr["msg"] = "successful";
 print_r(json_encode($final_arr));

 }else{

 $final_arr=array();
 $final_arr["status"] = "401";
 $final_arr["msg"] = "Not successful";
 print_r(json_encode($final_arr));
 }
 } 
 else
 {

 $final_arr=array();
 $final_arr["status"] = "501";
 $final_arr["msg"] = "Unsccessfull";
 print_r(json_encode($final_arr));

 }

//function to validate base64 string 
 function validateString($string)
 {
 $data = explode(',', $string);
 if(count($data) >= 2)
 {
 $format = explode('/', $data[0]);
 if($format[0] == 'data:image')
 {
 return true;
 }
 }
 return false;
 }

?>

但是,当使用python设置http服务器时,我设法发送和接收了http POST,因此我认为问题出在服务器端。谁能告诉我我做错了什么以及如何解决?

1 个答案:

答案 0 :(得分:0)

您可以通过邮递员api测试您的网址吗?如果您收到邮递员的任何错误,则说明您的api / url /服务器有问题。 另一件事是尝试上传经过改造的图像。简单而简单