Problem downloading image from Android to Mysql

I am working on a social application and I want to upload an image to a database, I tried the code and it worked. The file is in my folder, but the problem is that the path could not get into the Mysql database, I realized that it was $_FILES['uploaded_file']['name']empty, but I do not know how to solve it.

AddStatus.java:

public class AddStatus extends AppCompatActivity implements View.OnClickListener  {
private ProgressDialog pDialog;
EditText status;
Button send,upload_img;
String user_id;
private TextView messageText;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String imagepath=null;
JSONParser jsonParser = new JSONParser();
private static final String upLoadServerUri = "http://192.168.1.10/social/addstatus.php";

private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_status);

    ImageView img= new ImageView(this);

    status =(EditText)findViewById(R.id.edt_status);
    send = (Button)findViewById(R.id.btn_send);
    upload_img = (Button) findViewById(R.id.btn_img);

    messageText  = (TextView)findViewById(R.id.messageText);
    imageview = (ImageView)findViewById(R.id.imageView_pic);
    send.setOnClickListener(this);
    upload_img.setOnClickListener(this);

    final Intent callingIntent = getIntent();
    user_id = callingIntent.getStringExtra("user_id");


}
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_send:

            dialog = ProgressDialog.show(AddStatus.this, "", "Uploading file...", true);
            messageText.setText("uploading started.....");
            new Thread(new Runnable() {
                public void run() {

                    uploadFile(imagepath);

                }
            }).start();

            String stat = status.getText().toString();
            Long ts = System.currentTimeMillis();
            String time = ts.toString();
            new addStatus().execute(stat,user_id,time);

            break;

        case R.id.btn_img:
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
            break;

        default:
            break;
    }

}


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

    if (requestCode == 1 && resultCode == RESULT_OK) {
        //Bitmap photo = (Bitmap) data.getData().getPath();

        Uri selectedImageUri = data.getData();
        imagepath = getPath(selectedImageUri);
        Bitmap bitmap= BitmapFactory.decodeFile(imagepath);
        imageview.setImageBitmap(bitmap);
        messageText.setText("Uploading file path:" +imagepath);

    }
}


public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

public int uploadFile(String sourceFileUri) {


    String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);

    if (!sourceFile.isFile()) {

        dialog.dismiss();

        Log.e("uploadFile", "Source File not exist :"+imagepath);

        runOnUiThread(new Runnable() {
            public void run() {
                messageText.setText("Source File not exist :"+ imagepath);
            }
        });

        return 0;

    }
    else
    {
        try {

            // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("enctype", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", fileName);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + fileName + "\"" + lineEnd);

            dos.writeBytes(lineEnd);

            // create a buffer of  maximum size
            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if(serverResponseCode == 200){

                runOnUiThread(new Runnable() {
                    public void run() {
                        String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                +" F:/wamp/wamp/www/uploads";
                        messageText.setText(msg);
                        Toast.makeText(AddStatus.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            dialog.dismiss();
            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("MalformedURLException Exception : check script url.");
                    Toast.makeText(AddStatus.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            dialog.dismiss();
            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Got Exception : see logcat ");
                    Toast.makeText(AddStatus.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                }
            });
        }
        dialog.dismiss();
        return serverResponseCode;

    } // End else block
}

public void onPause() {

    super.onPause();
    if (pDialog != null)
        pDialog.dismiss();
}
class addStatus extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AddStatus.this);
        pDialog.setMessage("Creating User...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        int success;
        String status = args[0];
        String user_id = args[1];
        String time = args[2];

        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("status", status));
            params.add(new BasicNameValuePair("user_id", user_id));
            params.add(new BasicNameValuePair("time", time));



            Log.d("request!", "starting");

            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                    upLoadServerUri, "POST", params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("User Created!", json.toString());
                return json.getString(TAG_MESSAGE);
            } else {
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));

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


        return null;
    }


    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null) {
            Toast.makeText(AddStatus.this, file_url, Toast.LENGTH_LONG).show();
        }
    }

}


}

addStatus.php

<?php

 error_reporting(E_ALL ^ E_DEPRECATED);


 $response = array();   

 $target_path = "";


  $file_upload_url = 'http://' . '192.168.1.10' . '/' . 'social' . '/' .             $target_path;


  if (isset($_FILES['uploaded_file']['name'])) {

$target_path = $target_path . basename($_FILES['uploaded_file']['name']);


$response['file_name'] = basename($_FILES['uploaded_file']['name']);


try {
    // Throws exception incase file is not being moved
    if (!move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path)) {
        // make error flag true
        $response['error'] = true;
        $response['message'] = 'Could not move the file!';
    }

    // File successfully uploaded
    $response['message'] = 'File uploaded successfully!';
    $response['error'] = false;
    $response['file_path'] = $file_upload_url . basename($_FILES['uploaded_file']['name']);
    $path = $file_upload_url . basename($_FILES['uploaded_file']['name']);

} catch (Exception $e) {
    // Exception occurred. Make error flag true
    $response['error'] = true;
    $response['message'] = $e->getMessage();
}
} else {


// File parameter is missing
$response['error'] = true;
$response['message'] = 'Not received any file!F';
}




   if (isset($_POST['user_id']) && isset($_POST['status']) && isset($_POST['time'])){


$status = $_POST['status'];
$user_id = $_POST['user_id'];
$time = $_POST['time'];



 require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();



 $result = mysql_query("INSERT INTO posts(user_id,text,time,image) VALUES('$user_id','$status','$time','$path')");



    if ($result) {
        $response["success"] = 1;
        $response["message"] = "User created";

        echo json_encode($response);        
    }
    else {
        $response["success"] = 0;
        $response["message"] = "Registration failed";

        echo json_encode($response);

    }
}
else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);
}
 ?>

I hope you can help me in this matter. Thanks.

+4
source share

Source: https://habr.com/ru/post/1627484/


All Articles