我有一个如下所示的代码,它从浏览器上传文件并保存在服务器中,一旦保存到服务器,我希望服务器连接到Pinata API,这样文件也可以保存到IPFS节点。
let data = new FormData();
const fileBuffer = Buffer.from(`./public/files/${fileName}`, 'utf-8');
data.append('file', fileBuffer, `${fileName}`);
axios.post('https://api.pinata.cloud/pinning/pinJSONToIPFS',
data,
{
headers: {
'Content-Type': `multipart/form-data; boundary= ${data._boundary}`,
'pinata_api_key': pinataApiKey,
'pinata_secret_api_key': pinataSecretApiKey
}
}
).then(function (response) {
console.log("FILE UPLOADED TO IPFS NODE", fileName);
console.log(response);
}).catch(function (error) {
console.log("FILE WASNT UPLOADED TO IPFS NODE", fileName);
console.log(error);
});我遇到的问题是,在创建我的文件的缓冲区并将其包装在formdata中之后,pinata API返回一个错误:
data: {
error: 'This API endpoint requires valid JSON, and a JSON content-type'
}如果我将数据转换为类似JSON.stringify(data)的字符串,并将content-type更改为application/json,则文件缓冲区将作为字符串成功上载。
我希望能很好地解释它,以获得解决方案。谢谢。
发布于 2020-12-30 00:07:46
看起来您正在尝试将一个文件上传到pinJSONToIPFS端点,该端点仅用于通过请求体传入的JSON。
在你的情况下,我建议使用皮纳塔的pinFileToIPFS endpoint
以下是基于他们的文档的一些示例代码,可能对您有所帮助:
//imports needed for this function
const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');
export const pinFileToIPFS = (pinataApiKey, pinataSecretApiKey) => {
const url = `https://api.pinata.cloud/pinning/pinFileToIPFS`;
//we gather a local file for this example, but any valid readStream source will work here.
let data = new FormData();
data.append('file', fs.createReadStream('./yourfile.png'));
return axios.post(url,
data,
{
maxContentLength: 'Infinity', //this is needed to prevent axios from erroring out with large files
headers: {
'Content-Type': `multipart/form-data; boundary=${data._boundary}`,
'pinata_api_key': pinataApiKey,
'pinata_secret_api_key': pinataSecretApiKey
}
}
).then(function (response) {
//handle response here
}).catch(function (error) {
//handle error here
});
};发布于 2021-07-03 20:20:38
将任何文件固定到IPFS的正确代码如下所示。
显然,即使是Pinata的支持人员也不知道这一点。您需要使用属性名filepath作为最后一个参数来设置一个对象。名称无关紧要,它可以是重复的,可以与其他名称相同,也可以是唯一的。
const url = "https://api.pinata.cloud/pinning/pinFileToIPFS";
const fileContents = Buffer.from(bytes);
const data = new FormData();
data.append("file", fileContents, {filepath: "anyname"});
const result = await axios
.post(url, data, {
maxContentLength: -1,
headers: {
"Content-Type": `multipart/form-data; boundary=${data._boundary}`,
"pinata_api_key": userApiKey,
"pinata_secret_api_key": userApiSecret,
"path": "somename"
}
});https://stackoverflow.com/questions/65478423
复制相似问题