how to upload to files to amazon EC2

2019-09-13 02:15发布

问题:

I am trying to upload files to an amazon EC2 from android. however whenever i go to upload the files I get a Unexpected response code 500 error. From what I uderstand this is because the user doesnt have the correct permissions to upload files to the database? I know that the problem is with the amazon EC2 instance rather than the code. but below is my php code for uploading to the server. first of all is that the correct way to enter the upload folder (/var/www/html/uploads) ? Any help on how i can get this working would be great.

<?php
if(isset($_POST['image'])){
    echo "in";
    $image = $_POST['image'];
    upload($_POST['image']);
    exit;
}
else{
    echo "image_not_in";
    exit;
}


function upload($image){
    $now = DateTime::createFromFormat('U.u', microtime(true));
    $id = "pleeease";

    $upload_folder = "/var/www/html/upload";
    $path = "$upload_folder/$id.jpg";

    if(file_put_contents($path, base64_decode($image)) != false){
        echo "uploaded_success"
    }
    else{
        echo "uploaded_failed";
    }
}

?>

回答1:

Just a few notes:

First, you should make sure to send your data from the app with the enctype of multipart/form-data before submitting to the server.

Second, try variants of this simplified code:

if(isset($_FILES['image']))
{
   $fileTmp = $_FILES['image']['tmp_name'];
   $fileName = $_FILES['image']['name'];

    move_uploaded_file($fileTmp, "/var/www/html/uploads/" . $fileName);
    echo "Success";
}
else
{
    echo "Error";
}

And finally, assuming you're using Apache and the user name is www-data, you'll need to make sure it can write to the upload folder:

sudo chown www-data:www-data /var/www/html/uploads
sudo chmod 755 /var/www/html/uploads