无法上传内容到WordPress文件夹/wp-content/uploads/woocommerce_uploads/

uinbv5nw  于 12个月前  发布在  WordPress
关注(0)|答案(1)|浏览(104)

我试图写一个Python脚本,将上传图像和PDF到WordPress。我想将图像上传到文件夹“/wp-content/uploads/”和pdf文件到文件夹“/wp-content/uploads/woocommerce_uploads/”。

import requests
import os

class UploadProductMedia:
    def __init__(self, media_endpoint, wordpress_username, wordpress_password):
        self.media_endpoint = media_endpoint
        self.wordpress_username = wordpress_username
        self.wordpress_password = wordpress_password
        pass

    def upload_media(self, file_path):
        print(f"Uploading media {file_path}")
        with open(file_path, 'rb') as file:
            # Prepare the data to send in the request
            data = {
                'file': (os.path.basename(file_path), file),
            }

            # Determine the upload directory based on the file type
            upload_directory = '/wp-content/uploads/'
            if file_path.lower().endswith(('.pdf')):
                upload_directory = '/wp-content/uploads/woocommerce_uploads/'
            print(f"Uploading to directory {upload_directory}")

            # Send a POST request to the media endpoint with authentication
            response = requests.post(f"{self.media_endpoint}?upload_to={upload_directory}", auth=(self.wordpress_username, self.wordpress_password), files=data)

            if response.status_code == 201:
                response_data = response.json()
                uploaded_media_uri = response_data.get('guid', {}).get('rendered', '')
                print(f'Successfully uploaded: {file_path}')
                return uploaded_media_uri
            else:
                print(f'Failed to upload: {file_path}')
                print(f'Response: {response.status_code} - {response.text}')
                return None

if __name__ == "__main__":
    # Example usage:
    print("=== Starting ===")
    
    for file in ["TestData\pear1.png", "TestData\pear1.pdf"]:
        UploadProductMedia('https://mysite.co.uk/wp-json/wp/v2/media', 'myusername', 'mypassword').upload_media(file)
    print("=== Finished ===")

控制台日志表明程序按预期工作。

=== Starting ===
Uploading media TestData\pear1.png
Uploading to directory /wp-content/uploads/
Successfully uploaded: TestData\pear1.png
Uploading media TestData\pear1.pdf
Uploading to directory /wp-content/uploads/woocommerce_uploads/
Successfully uploaded: TestData\pear1.pdf
=== Finished ===

但是,pdf文件被上传到错误的目录。PDF已上传到https://mysite.co.uk/wp-content/uploads/2023/09/pear1.pdf
请,你能帮助解释为什么pdf文件没有被上传到/wp-content/uploads/woocommerce_uploads/

mspsb9vt

mspsb9vt1#

如果有人遇到同样的问题。我无法找到解决媒体上传问题的方法。我实现了一个变通方案,使用SFTP将文件上传到Web服务器。SFTP代码位于存储库https://github.com/seafooood/WooSpeedy/blob/main/ServiceUploadProductFtp.py

相关问题