无法使用Wordpress Media Rest API从React上传图像

时间:2019-08-25 00:31:04

标签: javascript reactjs multipartform-data wordpress-rest-api

我正在构建一个React应用程序(带有create-react-app),我需要使用Wordpress Media Rest API在Wordpress网站上上传图像。我正在本地运行React应用(http://localhost:3000/test) 在Wordpress网站上,我正在使用“用于WP-API的JWT身份验证”插件,以简化身份验证。

当我尝试上传图片时,它会显示“ 400-错误的请求”响应,并提供以下详细信息:

{"code":"rest_upload_no_data","message":"No data supplied.","data":{"status":400}}

我一直在搜索并尝试最近3天找到的所有解决方案。它们都不起作用。

我的实施细节:

在wp-config中,我做了plugin's page中描述的所有更改。

WP服务器.htaccess

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1 
#RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Content-Length, Cache-Control, Content-Disposition, Accept"
</IfModule>

# END WordPress

# BEGIN cPanel-generated php ini directives, do not edit
# Manual editing of this file may result in unexpected behavior.
# To make changes to this file, use the cPanel MultiPHP INI Editor (Home >> Software >> MultiPHP INI Editor)
# For more information, read our documentation (https://go.cpanel.net/EA4ModifyINI)
<IfModule php7_module>
   php_flag display_errors Off
   php_value max_execution_time 30
   php_value max_input_time 60
   php_value max_input_vars 1000
   php_value memory_limit 256M
   php_value post_max_size 260M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php72"
   php_value upload_max_filesize 256M
   php_flag zlib.output_compression Off

</IfModule>
<IfModule lsapi_module>
   php_flag display_errors Off
   php_value max_execution_time 30
   php_value max_input_time 60
   php_value max_input_vars 1000
   php_value memory_limit 256M
   php_value post_max_size 260M
   php_value session.gc_maxlifetime 1440
   php_value session.save_path "/var/cpanel/php/sessions/ea-php72"
   php_value upload_max_filesize 256M
   php_flag zlib.output_compression Off
</IfModule>
# END cPanel-generated php ini directives, do not edit

反应

const Test = () => {

    const [isUploading, setIsUploading] = useState(false)
    const [selectedFile, setSelectedFile] = useState(null)
    const blockScreenContext = useContext(BlockScreenUIContext)

    const fileUploadHandler = e => {

        e.preventDefault();

        //setting the data that will parsed with the file
        let oDate = new Date();
        let wpMediaData = {
            title: 'Posted from App',
            caption: 'The post caption text'
        }


        //creating the form data object and appending the extra info for the file
        let formData = new FormData();
        for (var key in wpMediaData) {
            formData.append(key, wpMediaData[key])
        }

        formData.append('file', selectedFile)
        //formData.append('file', document.querySelector('input[type="file"]').files[0])

        //defining the base url
        let baseUrl = 'https://mywebsite.com/'


        //getting the token
        let token = 'my token'

            let headers = {
                Authorization: 'Bearer ' + token,
                'Content-Type': 'multipart/form-data; charset=utf-8; boundary=' + Math.random().toString().substr(2),
                'Content-Disposition': `form-data; filename="${selectedFile.name}"`,
                'Cache-Control': 'no-cache',
            }


            const options = {
                method: 'POST',
                body: formData,
                headers: headers
            }

            let url = baseUrl + 'wp-json/wp/v2/media'

            fetch( url, options).then(res => {
                console.log('response', res)

            }).catch(err => {
                console.log('error', err)
            })


    }

    const fileSelectedHandler = e => {
        //the first element of the target is the file
        console.log('o valor obtido com e.target', e.target.files[0])
        setSelectedFile(e.target.files[0])
    }

    return <div>
        <form method="POST" encType="multipart/form-data">
            <div className="form-group">
                <input id="file" name="file" type="file" className="form-control" onChange={fileSelectedHandler} />
            </div>
            <div className="form-group">
                <BSButton
                    type='submit'
                    className='btn-primary'
                    text="Upload"
                    loadingText="Uploading..."
                    onClick={fileUploadHandler}
                    disable={isUploading}
                />
            </div>

        </form>
    </div>
}

对于内容处置,我也尝试过:

Content-Disposition': `attachment; filename=${selectedFile.name}

我尝试改用Axios,但遇到了同样的问题。 使用Wordpress的所有其他请求都可以正常工作。 预先谢谢你!

0 个答案:

没有答案