加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Android使用Volley库将图像上传到服务器

发布时间:2020-12-13 22:24:08 所属栏目:PHP教程 来源:网络整理
导读:我想使用排球库将我拍摄的图像从相机上传到我的000webhost.com服务器. 我想要在哪里出错,并建议我完整的代码解决方案. 我曾尝试编写代码,但它不起作用. 我收到如下错误: D/URL﹕ http:/plantnow.net16.net/uploaded.phpD/ERROR﹕ Error [com.android.volley
我想使用排球库将我拍摄的图像从相机上传到我的000webhost.com服务器.

我想要在哪里出错,并建议我完整的代码解决方案.

我曾尝试编写代码,但它不起作用.

我收到如下错误:

D/URL﹕ http:/plantnow.net16.net/uploaded.php
D/ERROR﹕ Error [com.android.volley.NoConnectionError: java.net.UnknownHostException:

“Cannot connect to server”

我的PHP uploaded.php看起来像这样.我想破坏服务器中的图像和图像路径.

<?php
 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
     $image = $_POST['image'];
     require_once('dbconnect.php');
     $sql ="SELECT id FROM images ORDER BY id ASC";
     $res = mysqli_query($con,$sql);
     $id = 0;

     while ($row = mysqli_fetch_array($res)) {
         $id = $row['id'];
     }

     $path = "uploadedimages/$id.jpeg";
     $actualpath = "http://plantnow.net16.net/$path";
     $sql = "INSERT INTO images (image) VALUES ('$actualpath')";

    if (mysqli_query($con,$sql)) {
        file_put_contents($path,base64_decode($image));
        echo "Successfully Uploaded";
    }

    mysqli_close($con);
} else {
    echo "Error";
}
?>

我的主要活动是凌空代码如下:

public class MainActivity extends Activity {
ProgressDialog prgDialog;
String encodedString;
String fileName;
private static int RESULT_LOAD_IMG = 1;
private Button buttonUploadPhoto;
private ImageView myimage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    prgDialog = new ProgressDialog(this);
    // Set Cancelable as False
    prgDialog.setCancelable(false);

    buttonUploadPhoto = (Button) findViewById(R.id.uploadPhoto);
    myimage = (ImageView) findViewById(R.id.imgView);



    buttonUploadPhoto.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            uploadImage();

        }
    });

}

public void loadImagefromGallery(View view) {
    // Create intent to Open Image applications like Gallery,Google Photos
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // Start the Intent
    startActivityForResult(galleryIntent,RESULT_LOAD_IMG);
}

// When Image is selected from Gallery
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
    super.onActivityResult(requestCode,resultCode,data);
    if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage,filePathColumn,null,null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        String fileNameSegments[] = picturePath.split("/");
        fileName = fileNameSegments[fileNameSegments.length - 1];

        Bitmap myImg = BitmapFactory.decodeFile(picturePath);
        myimage.setImageBitmap(myImg);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        // Must compress the Image to reduce image size to make upload easy
        myImg.compress(Bitmap.CompressFormat.PNG,50,stream);
        byte[] byte_arr = stream.toByteArray();
        // Encode Image to String
        encodedString = Base64.encodeToString(byte_arr,0);

        uploadImage();
    }
}



/**
 * API call for upload selected image from gallery to the server
 */
public void uploadImage() {

    RequestQueue rq = Volley.newRequestQueue(this);
    String url = "http:/plantnow.net16.net/uploaded.php";
    Log.d("URL",url);
    StringRequest stringRequest = new StringRequest(Request.Method.POST,url,new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            try {
                Log.e("RESPONSE",response);
                JSONObject json = new JSONObject(response);

                Toast.makeText(getBaseContext(),"The image is upload",Toast.LENGTH_SHORT)
                        .show();

            } catch (JSONException e) {
                Log.d("JSON Exception",e.toString());
                Toast.makeText(getBaseContext(),"Error while loadin data!",Toast.LENGTH_LONG).show();
            }

        }

    },new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("ERROR","Error [" + error + "]");
            Toast.makeText(getBaseContext(),"Cannot connect to server",Toast.LENGTH_LONG)
                    .show();
        }
    }) {
        @Override
        protected Map<String,String> getParams() {
            Map<String,String> params = new HashMap<String,String>();

            params.put("image",encodedString);
            params.put("filename",fileName);

            return params;

        }

    };
    rq.add(stringRequest);
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    // Dismiss the progress bar when application is closed
    if (prgDialog != null) {
        prgDialog.dismiss();
    }
}

解决方法

这对我来说似乎是一个错字.

尝试改变:

String url = "http:/plantnow.net16.net/uploaded.php"

至 :

String url = "http://plantnow.net16.net/uploaded.php"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读