
Upload example using JavaScript
You'll need
Node.js installed on your local system for this example.
1. Make a new JavaScript project.
Create a new directory and use npm to create a new project:
mkdir storj-ipfs-quickstart
cd storj-ipfs-quickstart
npm init
NPM will ask a few questions about your project and create a package.json file.
2. Add the axios HTTP client to your project dependencies.
Install the latest version of the axios package:
3. Create a file called upload.js and open it with your code editor.
Below is the code we need to upload a file and pin it on the Storj IPFS pinning service.
Paste in the code below and read through it. Feel free to remove the comments - they're just there to highlight what’s going on.
// The 'axios' module gives a promised-based HTTP client.
const axios = require('axios');
// The 'fs' builtin module provides us access to the file system.
const fs = require('fs');
// The 'form-data' builtin module helps us submit forms and file uploads
// to other web applications.
const FormData = require('form-data');
/**
* Uploads a file from `filepath` and pins it to the Storj IPFS pinning service.
* @param {string} filepath the path to the file
*/
async function pinFileToIPFS(filepath) {
// The HTTP upload endpoint of the Storj IPFS pinning service
const url = `https://demo.storj-ipfs.com/api/v0/add`;
// Create a form with the file to upload
let data = new FormData();
data.append('file', fs.createReadStream(filepath));
// Execute the Upload request to the Storj IPFS pinning service
return axios.post(url,
data,
{
headers: {
'Content-Type': `multipart/form-data; boundary= ${data._boundary}`,
},
// These arguments remove any client-side upload size restrictions
maxContentLength: Infinity,
maxBodyLength: Infinity,
},
).then(function (response) {
console.log(response)
}).catch(function (error) {
console.error(error)
});
};
/**
* The main entry point for the script that checks the command line arguments and
* calls pinFileToIPFS.
*
* To simplify the example, we don't do any fancy command line parsing. Just three
* positional arguments for imagePath, name, and description
*/
async function main() {
const args = process.argv.slice(2)
if (args.length !== 1) {
console.error(`usage: ${process.argv[0]} ${process.argv[1]} `)
process.exit(1)
}
const filepath = args[0]
const result = await pinFileToIPFS(filepath)
console.log(result)
}
/**
* Don't forget to actually call the main function!
* We can't `await` things at the top level, so this adds
* a .catch() to grab any errors and print them to the console.
*/
main()
.catch(err => {
console.error(err)
process.exit(1)
})
4. Run your script with node.
You should now be able to run the script and give it the path to a file.
node upload.js path/file.extension