如何使用php html在数据库上上传pdf文件

时间:2017-08-30 02:49:22

标签: java php

我如何在html上上传pdf文件与我的数据库上的相同。哪个是url和文件路径。所以,如果我要在Android工作室检索它,我可以知道路径和网址在哪里。请提供一些代码,可以在我的数据库中执行相同的操作。我已经在android studio上完成了这个。但我不知道我怎么能用html做到这一点

this is my database

和代码,但这是在android studio中完成的。我想在html上创建这个就像这样做#



<?php

//importing dbDetails file7     
require_once 'dbDetails.php';

//this is our upload folder
$upload_path = 'AndroidPdfUpload/';

//Getting the server ip
$server_ip = "files.000webhost.com";

//creating the upload url
$upload_url = 'https://cedportfolio.000webhostapp.com/AndroidPdfUpload/';

//response array
$response = array();


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

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

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

        //getting name from the request
        $name = $_POST['name'];

        //getting file info from the request
        $fileinfo = pathinfo($_FILES['pdf']['name']);

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

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

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

        //trying to save the file in the directory
        try{
            //saving the file
            move_uploaded_file($_FILES['pdf']['tmp_name'],$file_path);
            $sql = "INSERT INTO `topics` (`id`, `url`, `name`) VALUES (NULL, '$file_url', '$name');";

            //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'] = $name;
            }
            //if some error occurred
        }catch(Exception $e){
            $response['error']=true;
            $response['message']=$e->getMessage();
        } 
        //closing the connection
        mysqli_close($con);
    }else{
        $response['error']=true;
        $response['message']='Please choose a file';
    }
    
    //displaying the response
    echo json_encode($response);
}

/*
We are generating the file name
so this method will return a file name for the image to be upload
*/
function getFileName(){
    $con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die('Unable to Connect...');
    $sql = "SELECT max(id) as id FROM topics";
    $result = mysqli_fetch_array(mysqli_query($con,$sql));

    mysqli_close($con);
    if($result['id']==null)
        return 1;
    else
        return ++$result['id'];
}
&#13;
&#13;
&#13;

0 个答案:

没有答案