我正在尝试使用 Wordpress rest API 将图像上传到 wordpress。
一切正常,但是没有上传正确的图像。但是,当我使用 Curl 图像时是正确的。
curl --request POST \
--url http://localhost/wordpress/wp-json/wp/v2/media/ \
--header "cache-control: no-cache" \
--header "content-disposition: attachment; filename=hh.jpg" \
--header "authorization: Basic token" \
--header "content-type: image/jpg" \
--data-binary "@C://Users/as/Desktop/App _Ideas/hh.jpg" \
Run Code Online (Sandbox Code Playgroud)
此卷曲请求工作正常。
现在,当我将请求转换为 Nodejs 时
request({
url: ' http://localhost/wordpress/wp-json/wp/v2/media/',
headers: {
'cache-control': 'no-cache',
'content-disposition': 'attachment; filename='+filename,
'content-type' : 'image/jpg',
'authorization' : 'Basic token'
},
encoding: null,
method: 'POST',
body: "@C://Users/as/Desktop/App _Ideas/hh.jpg",
encoding: null
}, (error, response, body) => {
if (error) {
res.json({name : error});
} else {
res.json(JSON.parse(response.body.toString()));
}
});
Run Code Online (Sandbox Code Playgroud)
我可以在上传图像时从 wordpress 接收 json 响应。但是,上传的图像不正确,因为传递的二进制数据不正确。
Wordpress 上传文件夹显示hh.jpg大小为 17 字节的文件。在用记事本编辑时,它显示@hh.jpg这意味着字符串数据被保存为 hh.jpg 而不是实际的二进制数据。
如何使用 Nodejs 正确传递二进制数据的任何想法。
Atu*_*rma 11
让它工作,我们需要使用创建一个文件流
fs.createReadStream(filename);
Run Code Online (Sandbox Code Playgroud)
fs 模块。
request({
url: 'http://localhost/wordpress/wp-json/wp/v2/media/',
method: 'POST',
headers: {
'cache-control': 'no-cache',
'content-disposition': 'attachment; filename=' + filename,
'content-type' : 'image/jpg',
'authorization' : 'Basic token'
},
encoding: null,
body: fs.createReadStream('C://Users/as/Desktop/App _Ideas/hh.jpg')
}, (error, response, body) => {
if (error) {
res.json({name : error});
} else {
res.json(JSON.parse(response.body.toString()));
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16207 次 |
| 最近记录: |