Ad

Image Is Not Uploading To The Server

I'm working on project that should have functionality to upload image to the server. In MainActivity i have 3 tabs. 1st tab has 2 buttons to capture image and select image from gallery. After selecting or capturing the image will be displayed to the new Activity called Upload activity. This upload activity has 1 imageview and 1 button upload image. I'm able to display image but problem in upload image. After click on Upload button, response coming from server and there is no errors in logcat still my image is not uploading to the server.

Upload Activity

public class Upload extends AppCompatActivity{

public static String URL = "https://smilestechno.000webhostapp.com/upload.php";
String filepath;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);

    final Button btnUpload = (Button) findViewById(R.id.btnUpload);

    ImageView imageview = (ImageView) findViewById(R.id.imageview);
    Intent intent = getIntent();
    if (intent == null){
        return;
    }
    final Uri imageUri = Uri.parse(intent.getStringExtra("image"));
    filepath = getPath(Upload.this, imageUri);

imageview.setImageURI(imageUri);

    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (filepath != null){
                imageUpload(filepath);

            }else {
                Toast.makeText(Upload.this, "Image not Selected", Toast.LENGTH_SHORT).show();
            }
        }
    });
 }

 private void imageUpload(final String imagePath){
     SimpleMultiPartRequest smr =  new SimpleMultiPartRequest(Request.Method.POST, URL, new Response.Listener<String>() {
         @Override
         public void onResponse(String response) {
             try {
                 JSONObject jsonObject = new JSONObject(response);
                 Toast.makeText(Upload.this, "Image Uploaded", Toast.LENGTH_SHORT).show();

             } catch (JSONException e) {
                 e.printStackTrace();
             }
         }
     }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(com.android.volley.error.VolleyError error) {
             Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
         }
     });
     smr.addFile("img", imagePath);
     MyApplication.getInstance().addToRequestQueue(smr);
 }


public static String getPath(Context context, Uri contentUri) {
    //copy file and send new file path
    File TEMP_DIR_PATH = new File(Environment.getExternalStorageDirectory(), "/My Children/Temp");
    TEMP_DIR_PATH.mkdir();
    String fileName = getFileName(contentUri);
    if (!TextUtils.isEmpty(fileName)) {
        File copyFile = new File(TEMP_DIR_PATH + File.separator + fileName);
        copy(context, contentUri, copyFile);
        return copyFile.getAbsolutePath();
    }
    return null;
}

public static String getFileName(Uri uri) {
    if (uri == null) return null;
    String fileName = null;
    String path = uri.getPath();
    int cut = path.lastIndexOf('/');
    if (cut != -1) {
        fileName = path.substring(cut + 1);
    }
    return fileName;
}

public static void copy(Context context, Uri srcUri, File dstFile) {
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
        if (inputStream == null) return;
        OutputStream outputStream = new FileOutputStream(dstFile);
        org.apache.commons.io.IOUtils.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

PHP script

<?php

$uploaddir = 'ImagesUpload/';
$uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);
echo "<p>";

if (copy($_FILES['uploadedfile']['tmp_name'], $uploadfile)) 
{
  echo "File is valid, and was successfully uploaded.\n";
  $servername = "localhost";
    $username = "xyz";
$password = "xyz";
$dbname = "xyz";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) 
{
die("Connection failed: " . $conn->connect_error);
} 

 $filename="ImagesUpload/".$_FILES["uploadedfile"]["name"];
$sql = "INSERT INTO ImgInfo (ImgStatus, ImgLink,ImgUploadDate) VALUES ('0', '$filename',CURRENT_TIMESTAMP)";

if ($conn->query($sql) === TRUE) 
{
echo "New record created successfully";
} else 
{
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

} 
else 
{
   echo "Upload failed";
}

echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";

?>

I tried this script. I created html page and i'm able to upload image from html using this script.

Ad

Answer

IMO you passing wrong key value of image to php check below code

<?php

$uploaddir = 'ImagesUpload/';
$uploadfile = $uploaddir . basename($_FILES['img']['name']); //change here key as mentioned in java file.
echo "<p>";

if (copy($_FILES['img']['tmp_name'], $uploadfile)) 
{
  echo "File is valid, and was successfully uploaded.\n";
  $servername = "localhost";
    $username = "xyz";
$password = "xyz";
$dbname = "xyz";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) 
{
die("Connection failed: " . $conn->connect_error);
} 

 $filename="ImagesUpload/".$_FILES["img"]["name"];
$sql = "INSERT INTO ImgInfo (ImgStatus, ImgLink,ImgUploadDate) VALUES ('0', '$filename',CURRENT_TIMESTAMP)";

if ($conn->query($sql) === TRUE) 
{
echo "New record created successfully";
} else 
{
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

} 
else 
{
   echo "Upload failed";
}

echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";

?>

OR

keep your previous php file as it is and use uploadedfile instead of img change below code in imageUpload(final String imagePath)

  smr.addFile("uploadedfile", imagePath); //change key here.
     MyApplication.getInstance().addToRequestQueue(smr);
Ad
source: stackoverflow.com
Ad