관리 메뉴

나만을 위한 블로그

[Android] Volley를 사용해 이미지, 텍스트를 같이 서버에 저장하는 법 본문

Android

[Android] Volley를 사용해 이미지, 텍스트를 같이 서버에 저장하는 법

참깨빵위에참깨빵_ 2020. 6. 22. 19:41
728x90
반응형

PHP 스크립트

 

<?php

// 이미지, 텍스트 정보를 받아 서버에 저장하는 파일
// https://www.youtube.com/watch?v=j6nOOK6iDE0
$conn = mysqli_connect("xx.xxx.xxx.xx", "root", "비밀번호", "데이터베이스명");
// mysqli_select_db($conn, "android_db");

$name = $_POST['t1'];
$design = $_POST['t2'];
$img = $_POST['upload'];

// 파일명에 임의의 난수를 부여해(rand()) jpg 확장자로 저장한다
$filename = "IMG".rand().".jpg";
/**
 * file_put_contents() : PHP에서 데이터 / 텍스트를 파일에 쓰는 데 사용되는 함수
 * int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
 */
file_put_contents("images/".$filename, base64_decode($img));

$qry = "INSERT INTO tbl_staff(id, name, desig, image) VALUES (NULL, '$name', '$design', '$filename')";
$res = mysqli_query($conn, $qry);

if ($res == true)
{
    echo "File Uploaded Successfully";
}
else
{
    echo "Couldn't upload file";
}

 

안드로이드 소스코드

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context="com.vocabulary.childvoca.SellUsed.VolleySellImageUploadActivity">

    <EditText
        android:id="@+id/t1"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:hint="Enter your name"
        android:textColor="#000"
        android:textSize="25sp" />

    <EditText
        android:id="@+id/t2"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:hint="Enter your designation"
        android:textColor="#000"
        android:textSize="25sp" />

    <ImageView
        android:id="@+id/img"
        android:layout_width="300dp"
        android:layout_height="200dp"
        android:layout_marginTop="50dp"
        android:src="@mipmap/ic_launcher" />

    <Button
        android:id="@+id/browse"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:padding="10dp"
        android:text="browse image" />

    <Button
        android:id="@+id/upload"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:background="@color/colorPrimary"
        android:padding="10dp"
        android:text="upload to server"
        android:textColor="#FFF" />

</LinearLayout>
import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.childvoca.R;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class VolleySellImageUploadActivity extends AppCompatActivity {

    public static final String TAG = "VolleySellImageUploadActivity";

    EditText t1, t2;
    Button browse, upload;
    ImageView img;
    Bitmap bitmap;
    String encodeImageString;

    private static final String url = "http://xx.xxx.xxx.xx/fileupload.php";

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

        img = findViewById(R.id.img);
        upload = findViewById(R.id.upload);
        browse = findViewById(R.id.browse);

        browse.setOnClickListener(view -> {
            Dexter.withActivity(VolleySellImageUploadActivity.this)
                    .withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                    .withListener(new PermissionListener() {
                        @Override
                        public void onPermissionGranted(PermissionGrantedResponse response)
                        {
                            Intent intent = new Intent(Intent.ACTION_PICK);
                            intent.setType("image/*");
                            startActivityForResult(Intent.createChooser(intent, "Browse Image"), 1);
                        }

                        @Override
                        public void onPermissionDenied(PermissionDeniedResponse response)
                        {

                        }

                        @Override
                        public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token)
                        {
                            token.continuePermissionRequest();
                        }
                    }).check();
        });

        upload.setOnClickListener(view -> {
            uploadDataToDB();
        });
    }

    private void uploadDataToDB()
    {
        t1 = (EditText) findViewById(R.id.t1);
        t2 = (EditText) findViewById(R.id.t2);
        final String name = t1.getText().toString().trim();
        final String dsg = t2.getText().toString().trim();

        StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response)
            {
                t1.setText("");
                t2.setText("");
                img.setImageResource(R.mipmap.ic_launcher);
                Toast.makeText(VolleySellImageUploadActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                Toast.makeText(VolleySellImageUploadActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError
            {
                Map<String, String> map = new HashMap<>();
                // 1번 인자는 PHP 파일의 $_POST['']; 부분과 똑같이 해줘야 한다
                map.put("t1", name);
                map.put("t2", dsg);
                map.put("upload", encodeImageString);
                return map;
            }
        };

        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        queue.add(request);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    {
        if (requestCode == 1 && resultCode == RESULT_OK && data != null)
        {
            Uri filePath = data.getData();
            try {
                InputStream inputStream = getContentResolver().openInputStream(filePath);
                bitmap = BitmapFactory.decodeStream(inputStream);
                img.setImageBitmap(bitmap);
                encodeBitmapImage(bitmap);
            }   catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void encodeBitmapImage(Bitmap bitmap)
    {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);

        byte[] bytesOfImage = byteArrayOutputStream.toByteArray();
        encodeImageString = android.util.Base64.encodeToString(bytesOfImage, Base64.DEFAULT);
    }
}
반응형
Comments