使用PHP和OLX API上传图像时出现问题。

huangapple go评论55阅读模式
英文:

Issue with image upload using PHP and OLX API

问题

我正在处理一个上传图片到OLX平台的PHP脚本,使用他们的API。然而,我在图片上传功能上遇到了问题。我已经按照OLX提供的文档进行了操作,但是图片没有成功上传。

以下是我的代码的简化版本:

// 包含必要的库并设置变量
// 进行身份验证并获取必要的数据

// 为OLX创建新的列表(成功完成)
// 遍历图片URL并尝试上传它们
foreach ($imageUrls as $imageUrl) {
    // 下载图片
    // 准备图片上传请求
    // 发送请求并处理响应
    // 清理并继续下一张图片
}

代码逻辑涉及从给定的URL下载图片,然后使用OLX API准备图片上传请求。然而,图片上传没有按预期工作,我得到了意外的结果。

我已经确认图片文件已正确下载,并验证了API调用中包含了必要的头部和请求参数。但是API的响应是成功的,但图片没有上传。

var_dump($response);

这行代码返回以下内容:

string(21) "{"message":"success"}"

我还尝试了其他方法,比如直接发送图片内容或使用不同的内容类型,但都没有解决问题。

有人可以请查看我的代码,并提供可能遗漏的内容或建议潜在的解决方案吗?我会非常感激任何对这个问题的帮助或见解。

你可以在这里找到他们的文档:图片上传文档

基本上,一切都很顺利,产品在网站上都可见,但是图片上传根本不起作用(我的意思是图片在网站上看不到),我无法弄清楚问题在哪里。

代码:

if (isset($res2_json['status']) && $res2_json['status'] === 'active') {
    $successCount++;
    echo "Product with SKU " . $product['sku'] . " published successfully.\n";

    // 从载荷中获取图片URL
    $imageUrls = explode(',', $product['images']); // 将图片URL拆分为数组
    $uploadUrl = "https://api.olx.ba/listings/{$product_id}/image-upload";

    // 获取PHP脚本文件的目录路径
    $scriptDirectory = dirname(__FILE__);

    // 创建一个数组来存储图片文件
    $imageFiles = array();

    // 遍历每个图片URL并下载它们
    foreach ($imageUrls as $imageUrl) {
        $imageUrl = trim($imageUrl); // 移除URL中的任何前导/尾随空格

        // 下载图片并将其保存在与PHP脚本文件相同的文件夹中
        $filename = basename($imageUrl);
        $localFilePath = $scriptDirectory . '/' . $filename;
        file_put_contents($localFilePath, file_get_contents($imageUrl));

        // 检查图片是否成功保存
        if (file_exists($localFilePath)) {
            // 为每个图片创建一个包含所需属性的数组
            $imageFile = array(
                'name' => 'images[]',
                'contents' => fopen($localFilePath, 'r'),
                'filename' => $filename,
            );

            // 将图片文件添加到数组中
            $imageFiles[] = $imageFile;
        } else {
            echo "Failed to save image: {$imageUrl}\n";
        }
    }

    // 创建包含图片文件的请求体
    $requestBody = array('images' => $imageFiles);

    // 设置头部
    $headers11 = array(
        "Content-Type: multipart/form-data",
        "OLX-CLIENT-ID: ",
        "OLX-CLIENT-TOKEN: "
    );

    // 创建流上下文选项
    $contextOptions = array(
        'http' => array(
            'method' => 'POST',
            'header' => implode("\r\n", $headers11),
            'content' => $requestBody,
        ),
    );

    // 创建流上下文
    $streamContext = stream_context_create($contextOptions);

    // 发送请求
    $response = file_get_contents($uploadUrl, false, $streamContext);

    // 根据需要处理图片上传响应
    // 例如,您可以检查响应状态码以确保上传成功
    if ($response !== false) {
        echo "Images uploaded successfully.\n";
    } else {
        echo "Failed to upload images.\n";
    }
    var_dump($response);

    // 删除本地图片文件
    foreach ($imageFiles as $imageFile) {
        $localFilePath = $scriptDirectory . '/' . $imageFile['filename'];
        unlink($localFilePath);
    }
} else {
    $failureCount++;
    echo "Failed to publish product with SKU " . $product['sku'] . ".\n";
}

更新 20.06(根据评论建议):

  1. $imageFiles 数组已被修改,直接存储图片内容,使用文件名作为键。这是通过将以下行替换:
$imageFile = array(
    'name' => 'images[]',
    'contents' => fopen($localFilePath, 'r'),
    'filename' => $filename,
);

替换为:

$imageFiles[$filename] = $imageContent;
  1. 请求体通过对 $imageFiles 数组进行JSON编码来创建:
$requestBody = json_encode(array('images' => $imageFiles));
  1. CURLOPT_POSTFIELDS 选项设置为 $requestBody,而不是 $imageFiles 数组:
CURLOPT_POSTFIELDS => $requestBody
  1. foreach 循环中的文件删除已更新为使用 $imageFiles 数组中的文件名作为键:
foreach ($imageFiles as $filename => $imageContent) {
    $localFilePath = $scriptDirectory . '/' . $filename;
    unlink($localFilePath);
}
英文:

I'm working on a PHP script that uploads images to the OLX platform using their API. However, I'm encountering issues with the image upload functionality. I have followed the documentation provided by OLX, but the images are not being uploaded successfully.

Here's a simplified version of my code:

// Include necessary libraries and setup variables
// Authenticate and get necessary data
// Creating new listing for OLX (successfully done) 
// Iterate over image URLs and attempt to upload them
foreach ($imageUrls as $imageUrl) {
// Download the image
// Prepare the image upload request
// Send the request and handle the response
// Clean up and proceed to the next image
}

The code logic involves downloading images from given URLs and then preparing the image upload request using the OLX API. However, the image upload is not working as expected, and I'm getting unexpected results.

I have confirmed that the image files are downloaded correctly and have verified that the necessary headers and request parameters are included in the API call. However, the response from the API is successful, and the images are not uploaded.
var_dump($response); -> this line of code returns this:

string(21) "{"message":"success"}"

I have also tried alternative approaches, such as directly sending the image contents or using different content types, but none of them have resolved the issue.

Could someone please review my code and provide guidance on what I might be missing or suggest any potential solutions? I would greatly appreciate any assistance or insights into this problem.

And you can find their docs here: Image-upload docs .

Basically, everything goes smoothly, product is visible and everything else on the site, but image upload simply doesn't work (by that I mean image is not visible on the site) and I can't figure out what's problem.

Code:

    if (isset($res2_json['status']) && $res2_json['status'] === 'active') {
$successCount++;
echo "Product with SKU " . $product['sku'] . " published successfully.\n";
// Get the image URLs from the payload
$imageUrls = explode(',', $product['images']); // Split the image URLs into an array
$uploadUrl = "https://api.olx.ba/listings/{$product_id}/image-upload";
// Get the directory path of the PHP script file
$scriptDirectory = dirname(__FILE__);
// Create an array to hold the image files
$imageFiles = array();
// Iterate over each image URL and download them
foreach ($imageUrls as $imageUrl) {
$imageUrl = trim($imageUrl); // Remove any leading/trailing spaces from the URL
// Download the image and save it locally in the same folder as the PHP script file
$filename = basename($imageUrl);
$localFilePath = $scriptDirectory . '/' . $filename;
file_put_contents($localFilePath, file_get_contents($imageUrl));
// Check if the image was saved successfully
if (file_exists($localFilePath)) {
// Create an array for each image with the required attributes
$imageFile = array(
'name' => 'images[]',
'contents' => fopen($localFilePath, 'r'),
'filename' => $filename,
);
// Add the image file to the array
$imageFiles[] = $imageFile;
} else {
echo "Failed to save image: {$imageUrl}\n";
}
}
// Create the request body with the image files
$requestBody = array('images' => $imageFiles);
// Set the headers
$headers11 = array(
"Content-Type: multipart/form-data",
"OLX-CLIENT-ID: ",
"OLX-CLIENT-TOKEN: "
);
// Create the stream context options
$contextOptions = array(
'http' => array(
'method' => 'POST',
'header' => implode("\r\n", $headers11),
'content' => $requestBody,
),
);
// Create the stream context
$streamContext = stream_context_create($contextOptions);
// Send the request
$response = file_get_contents($uploadUrl, false, $streamContext);
// Handle the image upload response as needed
// For example, you can check the response status code to ensure the upload was successful
if ($response !== false) {
echo "Images uploaded successfully.\n";
} else {
echo "Failed to upload images.\n";
}
var_dump($response);
// Delete the local image files
foreach ($imageFiles as $imageFile) {
$localFilePath = $scriptDirectory . '/' . $imageFile['filename'];
unlink($localFilePath);
}
}                          
else {
$failureCount++;
echo "Failed to publish product with SKU " . $product['sku'] . ".\n";
}`

Update 19.06 (17:36) - by suggestion from comments I've refactured code to use cURL, didn't resolve the problem, same problem persist from earlier:

if (isset($res2_json['status']) && $res2_json['status'] === 'active') {
$successCount++;
echo "Product with SKU " . $product['sku'] . " published successfully.\n";
// Get the image URLs from the payload
$imageUrls = explode(',', $product['images']); // Split the image URLs into an array
var_dump($imageUrls);
$uploadUrl = "https://api.olx.ba/listings/{$product_id}/image-upload";
// Get the directory path of the PHP script file
$scriptDirectory = dirname(__FILE__);
// Create an array to hold the image files
$imageFiles = array();
// Iterate over each image URL and download them
foreach ($imageUrls as $imageUrl) {
$imageUrl = trim($imageUrl); // Remove any leading/trailing spaces from the URL
var_dump($imageUrls);
// Download the image and save it locally in the same folder as the PHP script file
$filename = basename($imageUrl);
$localFilePath = $scriptDirectory . '/' . $filename;
// Initialize cURL
$ch = curl_init($imageUrl);
// Set the cURL options for downloading the image
$downloadOptions = array(
CURLOPT_RETURNTRANSFER => true,
);
// Set the cURL options
curl_setopt_array($ch, $downloadOptions);
// Execute the request and get the image content
$imageContent = curl_exec($ch);
// Check for errors
if ($imageContent === false) {
echo "Failed to download image: {$imageUrl}. Error: " . curl_error($ch) . "\n";
continue;
}
// Save the image content to a local file
file_put_contents($localFilePath, $imageContent);
// Check if the image was saved successfully
if (file_exists($localFilePath)) {
// Create an array for each image with the required attributes
$imageFile = array(
'name' => 'images[]',
'contents' => fopen($localFilePath, 'r'),
'filename' => $filename,
);
// Add the image file to the array
$imageFiles[] = $imageFile;
} else {
echo "Failed to save image: {$imageUrl}\n";
}
// Close cURL
curl_close($ch);
}
// Initialize cURL
$ch = curl_init();
// Set the cURL options
$options = array(
CURLOPT_URL => $uploadUrl,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
"Content-Type: multipart/form-data",
"OLX-CLIENT-ID: ",
"OLX-CLIENT-TOKEN: "
),
CURLOPT_POSTFIELDS => $imageFiles
);
// Set the cURL options
curl_setopt_array($ch, $options);
// Send the request and capture the response
$response = curl_exec($ch);
// Check for errors
if ($response === false) {
echo "Failed to upload images. Error: " . curl_error($ch) . "\n";
} else {
echo "Images uploaded successfully.\n";
var_dump($response);
}
// Close cURL
curl_close($ch);
// Delete the local image files
foreach ($imageFiles as $imageFile) {
$localFilePath = $scriptDirectory . '/' . $imageFile['filename'];
unlink($localFilePath);
}
}

UPDATE 20.06 (as per suggestions from comments):

  1. The $imageFiles array is modified to store the image content directly, using the filename as the key. This is done by replacing the line:

    $imageFile = array(
        'name' => 'images[]',
        'contents' => fopen($localFilePath, 'r'),
        'filename' => $filename,
    );
    

    with:

    $imageFiles[$filename] = $imageContent;
    
  2. The request body is created by JSON-encoding the $imageFiles array:

    $requestBody = json_encode(array('images' => $imageFiles));
    
  3. The CURLOPT_POSTFIELDS option is set to the $requestBody instead of the $imageFiles array:

    CURLOPT_POSTFIELDS => $requestBody
    
  4. The file deletion in the foreach loop is updated to use the filename as the key in the $imageFiles array:

    foreach ($imageFiles as $filename => $imageContent) {
        $localFilePath = $scriptDirectory . '/' . $filename;
        unlink($localFilePath);
    }
    

答案1

得分: 0

我只想说,我决定使用Guzzle后成功解决了问题。

我不得不完全重构代码,但没关系。此外,最后我决定使用Bearer令牌,因为我觉得它更合适。

if (isset($res2_json['status']) && $res2_json['status'] === 'active') {
    $successCount++;
    echo "Product with SKU " . $product['sku'] . " published successfully.\n";

    // Get the image URLs from the payload
    $imageUrls = explode(',', $product['images']); // Split the image URLs into an array

    // Prepare the image upload URL
    $uploadUrl = "https://api.olx.ba/listings/{$product_id}/image-upload";

    // Create a Guzzle client instance
    $client = new Client();

    // Create an array to hold the image files
    $imageFiles = [];

    // Iterate over each image URL and upload them
    foreach ($imageUrls as $imageUrl) {
        $imageUrl = trim($imageUrl);

        // Send a GET request to download the image
        $response = $client->get($imageUrl);

        // Get the image content from the response
        $imageContent = $response->getBody()->getContents();

        // Append the image to the image files array
        $imageFiles[] = [
            'name' => 'images[]',
            'contents' => $imageContent,
            'filename' => basename($imageUrl)
        ];
    }

    try {
        // Send a POST request using Guzzle
        $response = $client->request('POST', $uploadUrl, [
            'multipart' => $imageFiles,
            'headers' => [
                'Authorization' => '',
            ],
        ]);

        echo "Images uploaded successfully.\n";
        var_dump($response->getBody()->getContents());
    } catch (Exception $e) {
        echo "Failed to upload images. Error: " . $e->getMessage() . "\n";
    }
} else {
    $failureCount++;
    echo "Failed to publish product with SKU " . $product['sku'] . ".\n";
}
英文:

I just want to say that I've fixed the problem successfully after deciding to go with Guzzle.

I had to completely refactor the code, but it's fine. Also, I've made decision to go with Bearer token at the end, because I found it more suitable.

if (isset($res2_json['status']) && $res2_json['status'] === 'active') {
$successCount++;
echo "Product with SKU " . $product['sku'] . " published successfully.\n";
// Get the image URLs from the payload
$imageUrls = explode(',', $product['images']); // Split the image URLs into an array
// Prepare the image upload URL
$uploadUrl = "https://api.olx.ba/listings/{$product_id}/image-upload";
// Create a Guzzle client instance
$client = new Client();
// Create an array to hold the image files
$imageFiles = [];
// Iterate over each image URL and upload them
foreach ($imageUrls as $imageUrl) {
$imageUrl = trim($imageUrl);
// Send a GET request to download the image
$response = $client->get($imageUrl);
// Get the image content from the response
$imageContent = $response->getBody()->getContents();
// Append the image to the image files array
$imageFiles[] = [
'name' => 'images[]',
'contents' => $imageContent,
'filename' => basename($imageUrl)
];
}
try {
// Send a POST request using Guzzle
$response = $client->request('POST', $uploadUrl, [
'multipart' => $imageFiles,
'headers' => [
'Authorization' => '',
],
]);
echo "Images uploaded successfully.\n";
var_dump($response->getBody()->getContents());
} catch (Exception $e) {
echo "Failed to upload images. Error: " . $e->getMessage() . "\n";
}
} else {
$failureCount++;
echo "Failed to publish product with SKU " . $product['sku'] . ".\n";
}

huangapple
  • 本文由 发表于 2023年6月19日 22:38:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76507663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定