简体   繁体   English

使用PHP上传AWS EC2文件

[英]AWS EC2 file upload with php

Im facing some problem with upload image to my wamp server which located in aws ec2 instance, When im trying to uplaod some parametrs into my tables, all the parametrs are uploaded succesfully except the image itself, the wamp server installed on Microsoft Windows Server 2012 R2 Base, which provided by amazon, port 80 opened, and so is the httpd.conf file with permissions. 我将图像上传到位于aws ec2实例中的Wamp服务器时遇到了一些问题,当我试图将某些参数上传到我的表中时,除图像本身(安装在Microsoft Windows Server 2012 R2上的Wamp服务器)外,所有参数均成功上传Base(由Amazon提供)打开了端口80,具有权限的httpd.conf文件也已打开。

here is the code from android which uploads the image and the parametrs: 这是来自android的代码,该代码上传了图像和参数:

public void uploadProduct() {
    //getting name for the image
    String name = editText.getText().toString().trim();
    String Description = editText2.getText().toString().trim();
    String Serial = editText3.getText().toString().trim();
    String price = editText4.getText().toString().trim();

    //getting the actual path of the image
    String path = getPath(fileUri);

    //Uploading code
    try {
        String uploadId = UUID.randomUUID().toString();

        //Creating a multi part request
        new MultipartUploadRequest(this, uploadId, URL_INDEX)
                .addFileToUpload(path, "image") //Adding file
                .addParameter("name", name)
                .addParameter("product_description", Description)
                .addParameter("product_serial", Serial)
                .addParameter("product_price", price)//Adding text parameter to the request
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload(); //Starting the upload

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

The code for getting image Uri: 获取图像Uri的代码:

 public String getPath(Uri uri) {
    String filePath = "";

    String wholeID = DocumentsContract.getDocumentId(uri);

    // Split at colon, use second item in the array
    String id = wholeID.split(":")[1];

    String[] column = { MediaStore.Images.Media.DATA };

    // where id is equal to
    String sel = MediaStore.Images.Media._ID + "=?";

    Cursor cursor = getApplicationContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            column, sel, new String[]{ id }, null);

    int columnIndex = cursor.getColumnIndex(column[0]);

    if (cursor.moveToFirst()) {
        filePath = cursor.getString(columnIndex);
    }
    cursor.close();
    return filePath;

}

and the php: 和PHP:

require_once 'db_config.php'; require_once'db_config.php';

$upload_path = 'uploads/'; $ upload_path ='上传/';

$upload_url = ' http://55.26.0.105/android/uploads/ '; $ upload_url =' http://55.26.0.105/android/uploads/ ';

$response = array(); $ response = array();

if($_SERVER['REQUEST_METHOD']=='POST'){ if($ _ SERVER ['REQUEST_METHOD'] =='POST'){

//checking the required parameters from the request
if( isset($_FILES['image']['name']) and isset($_POST['name']) and isset($_POST['product_description']) and isset($_POST['product_serial']) and isset($_POST['product_price'])){

    //connecting to the database
    $con = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die('Unable to Connect...');

    //getting values from the request
    $product_serial_num = (int) $_POST['product_serial'];
    $product_price = (int) $_POST['product_price'];
    $product_title = $_POST['name'];
    $product_description = $_POST['product_description'];


    //getting img info from the request
    $fileInfo = pathinfo($_FILES['image']['name']);

    //getting the file extension
    $extension = $fileInfo['extension'];

    //file url to store in the database
    $file_url = $upload_url . $product_title . '.' . $extension;

    //file path to upload in the server
    $file_path = $upload_path . $product_title . '.'. $extension;

    //trying to save the file in the directory
    try{
        //saving the file
        move_uploaded_file($_FILES['image']['tmp_name'],$file_path);
        $sql = "INSERT INTO product_tbl(product_serial_num, product_price, product_title, product_description, product_img) VALUES ('$product_serial_num','$product_price','$product_title','$product_description', '$file_url');";

        //adding the path and name to database
        if(mysqli_query($con,$sql)){

            //filling response array with values
            $response['error'] = false;
            $response['url'] = $file_url;
            $response['name'] = $product_title;
        }
        //if some error occurred
    }catch(Exception $e){
        $response['error']=true;
        $response['message']=$e->getMessage();
    }
    //displaying the response
    echo json_encode($response);

    //closing the connection
    mysqli_close($con);
}else{
    $response['error']=true;
    $response['message']='Please choose a file';
}

} ?> }?>

Any help would be appriciated, thanks a lot! 任何帮助将不胜感激,非常感谢!

Probable causes : 可能的原因:

  1. The PHP Script that is saving the uploaded file is in some other location where there is no 'uploads' directory. 保存上载文件的PHP脚本位于其他没有“上载”目录的位置。
  2. No proper access rights given to the 'uploads' directory(less probable in Windows Server). 没有对“上载”目录给予适当的访问权限(在Windows Server中可能性较小)。

Solutions : 解决方案:

  1. Try using a static path for uploads location. 尝试使用静态路径上传位置。 Seeing your code, you better define the path in 'db_config.php' file itself. 看到您的代码,您最好在“ db_config.php”文件本身中定义路径。
  2. Set proper access rights by going to properties of the 'uploads' directory. 通过转到“上载”目录的属性来设置适当的访问权限。

And to confirm if the file is uploaded successfully or not, you should wrap your move_uploaded_file($_FILES['image']['tmp_name'],$file_path); 为了确认文件是否成功上传,您应该包装move_uploaded_file($_FILES['image']['tmp_name'],$file_path); in a if() condition. if()条件下。

Since PHP move_uploaded_file() function returns true if the file is uploaded successfully, or false otherwise. 由于PHP move_uploaded_file()函数成功上传文件,则返回true ,否则返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM