user3927675
user3927675

Reputation:

Image data sends to Database but file does not upload to server

I am currently making an application on android where a user will be able to upload an Image with a title and description to a database and godaddy server.

When I test the code, the data is inserted in the database, however the Image does not appear or send to the specified file.

I have a number of suspicions what the problem might be. Doing some research I see people recommending Multipart request to solve the problem, but I do not see how that would solve it. I was thinking it may be something to do with server permissions?

Here is my code:

UploadActivity.java

public class UploadActivity extends ActionBarActivity implements View.OnClickListener{

private Button bBrowse;
private Button bUpload;

private TextView tvFileInfo;

// private ImageView imageView;

private EditText enTitle;
private EditText enDescription;

private Bitmap bitmap;

private int PICK_IMAGE_REQUEST = 1;

private String UPLOAD_URL = "http://opuna.co.uk/Upload%20api/Upload.php";

private String KEY_IMAGE = "image";
private String KEY_TITLE = "Title";
private String KEY_DESC = "Description";


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

    bBrowse = (Button) findViewById(R.id.bBrowse);
    bUpload = (Button) findViewById(R.id.bUpload);

    enTitle = (EditText) findViewById(R.id.enTitle);
    enDescription = (EditText) findViewById(R.id.enDescription);

    tvFileInfo = (TextView) findViewById(R.id.tvFileInfo);

    bBrowse.setOnClickListener(this);
    bUpload.setOnClickListener(this);

}


public String getStringImage(Bitmap bmp) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

private void uploadImage() {
    //Showing the progress dialog
    final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
    StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    //Disimissing the progress dialog
                    loading.dismiss();
                    //Showing toast message of the response
                    Toast.makeText(UploadActivity.this, s, Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss();

                    //Showing toast
                    Toast.makeText(UploadActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            //Converting Bitmap to String
            String image = getStringImage(bitmap);

            //Getting Image Name
            String Title = enTitle.getText().toString().trim();
            String Description = enDescription.getText().toString().trim();

            //Creating parameters
            Map<String, String> params = new Hashtable<String, String>();

            //Adding parameters
            params.put(KEY_IMAGE, image);
            params.put(KEY_TITLE, Title);
            params.put(KEY_DESC, Description);


            //returning parameters
            return params;
        }
    };

    //Creating a Request Queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);

    //Adding request to the queue
    requestQueue.add(stringRequest);
}

private void showFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_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 {
            //Getting the Bitmap from Gallery
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            //Setting the Bitmap to ImageView
            //imageView.setImageBitmap(bitmap);
            tvFileInfo.setText("File Selected: " + filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

@Override
public void onClick(View v) {

    if (v == bBrowse) {
        showFileChooser();
    }

    if (v == bUpload) {
        uploadImage();
    }
}
}

And here is the Upload.php

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){
            $image = $_POST['image'];
            $Title = $_POST['Title'];
            $Description = $_POST['Description'];


require_once('DatabaseConnect.php');
$sql ="SELECT id FROM Photos ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.png"; //Possibly change to match file path of Subject    ID


$actualpath = "http://opuna.co.uk/$path";

$sql = "INSERT INTO Photos (image,Title,Description) VALUES    ('$actualpath','$Title', '$Description')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error"; 
}
?>

I also keep getting this error:

E/Volley: [334] BasicNetwork.performRequest: Unexpected response code 500 for http://opuna.co.uk/Upload%20api/Upload.php

any help will be appreciated!

Upvotes: 0

Views: 345

Answers (1)

Umesh Singh Kushwaha
Umesh Singh Kushwaha

Reputation: 5741

You should check your server permission. I looks your PHP script, multipart request from client is must.To implement multipart using Volly, follow the following link .

you can refer following links:

Working POST Multipart Request with Volley and without HttpEntity

How to send a “multipart/form-data” POST in Android with Volley

Trouble Sending Multipart File with Boundary via Volley

Upvotes: 1

Related Questions