在php中创建动态文件上传api


Create Dynamic fileupload api in php

我正在php中开发文件上传api。现在,我只创建了这个简单的php,它将把文件从html页面上传到服务器。但在这段代码中,fileupload控件的名称是固定的,所以我在上传文件的php代码中传递了这个名称。但我想为第三方创建这个api。如果有人要求api,那么我会给出我的api链接,他们会消费它。现在任何人都请帮助我将其转换为动态

这是html代码

<html>
<head>
 </head>
 <body>
 <h2>Upload Image </h2>
<form action="http://mvcangularworld.com/api.php" method="POST" enctype="multipart/form-data" >
<input type="file" name="filename" value="" />
<br />
<input type="submit" value="Upload File"  />
</form>
</body>
</html>

这是我的api.php 的php代码

<?php
// Path to move uploaded files
$target_path = 'images/';

$response = array();

$file_upload_url = $target_path;
$filename = $_POST['filename']; 
 if (isset($_FILES['filename']['name'])) 
{
    $target_path = $target_path . basename($_FILES['filename']['name']);
    // reading other post parameters
    echo $_FILES['filename']['name']."<br />";
    echo $_FILES['filename']['tmp_name']."<br />";
    $response['file_name'] = basename($_FILES['filename']['name']);
    try 
    {
        // Throws exception incase file is not being moved
        if (!move_uploaded_file($_FILES['filename']['tmp_name'], $target_path)) 
        {
            // make error flag true
            $response['error'] = true;
            $response['message'] = 'Could not move the file!';
        }
        // File successfully uploaded
         //echo $file_upload_url . basename($_FILES['filename']['name']);
        $response['message'] = 'File uploaded successfully!';
        $response['error'] = false;
        $response['file_path'] = $file_upload_url . basename($_FILES['filename']['name']);
    } 
    catch (Exception $e) 
    {
        // Exception occurred. Make error flag true
        $response['error'] = true;
        $response['message'] = $e->getMessage();
    }
} 
//else 
//{ 
    // File parameter is missing
 /*    $response['error'] = true;
    $response['message'] = 'Not received any file';
} */
// Echo final json response to client
echo
 json_encode($response, JSON_UNESCAPED_SLASHES);
?>

这是api链接

http://mvcangularworld.com/api.php

请帮助我使这个api动态

一个简单的解决方案可以是,添加一个隐藏字段,该字段具有文件字段的名称,如:

<input type="hidden" name="fileFieldName" value="filename" />

服务器端:

$fileFieldName = $_POST['fileFieldName'];
move_uploaded_file($_FILES[$fileFieldName]['tmp_name']