如何使用JAVA在服务器上上传图片?

时间:2018-11-28 20:24:18

标签: java php database server

<?php 

require_once 'dbDetails.php';

$upload_path = 'uploads/';

$server_ip = gethostbyname(gethostname());

$upload_url = 'http://'.$server_ip.'/UploadExample/'.$upload_path;

$response = array(); 

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    if(isset($_POST['name']) and isset($_FILES['image']['name'])){
        $con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME) or die('unable to connect to database ');
        $name = $_POST['name'];

        $fileinfo = pathinfo($_FILES['image']['name']);

        $extension = $fileinfo['extension'];

        $file_url = $upload_url . getFileName() . '.'.$extension; 

        $file_path = $upload_path. getFileName(). '.'.$extension; 

        try{

            move_uploaded_file($_FILES['image']['tmp_name'], $file_path);

            $sql = "INSERT INTO images (url, name) VALUES ('$file_url','$name')";
            if(mysqli_query($con,$sql)){
                $response['error'] = false; 
                $response['url'] = $file_url; 
                $response['name'] = $name; 
            }

        }catch(Exception $e){
            $response['error'] = false; 
            $response['message'] = $e->getMessage(); 
        }
        mysqli_close($con);

    }else{
        $response['error'] = true; 
        $response['message'] = 'please choose a file';
    }

    echo json_encode($response);
}

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 images";
    $result = mysqli_fetch_array(mysqli_query($con,$sql));
    mysqli_close($con);
    if($result['id']==null){
        return 1; 
    }else{
        return ++$result['id'];
    }
}

我正在使用此代码获取图像的URL,并将URL存储在我的数据库中。但是我们不能在php中使用诸如连接池之类的方法来处理大型连接。有没有其他选择可以使我可以用JAVA编写此代码,也可以使用其他可以在php中使用的连接池方法?

0 个答案:

没有答案