How to get a public URL from MFS folder? - file

So ipfs gives us https based urls for files yet they are all unique, per-file and hash based. I want to get something like that yet for expandable folders with updatable files (say have ‘parent hash/{fileIdPath}’ link). How to get a link to a file from the ipfs Mutable File System (MFS) (a link that would stay the same after I update the file)?

If I am understand the question you want to get access to the URL from a hash file path, please post your code so we can see what you have tried so far and what specifically is the issue
Here is a ref to IPFS
You will need a clients to access those resources over http
For e.g. ipfs-http-client, js-ipfs for js access
using ipfs-http-client
please install it like so
//npm install ipfs-http-client#42.0.1 if you want a specific version
npm install --save ipfs-http-client
Setup your permissions
$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin '["http://example.com"]'
$ ipfs config --json API.HTTPHeaders.Access-Control-Allow-Methods '["PUT", "POST", "GET"]'
Now you can access the information with client
const ipfs = window.IpfsHttpClient()
sample js
With the JS client, install js-ipfs
import { create } from 'ipfs-http-client'
const client = create()
// add your addres below and get the contents
// dor e.g. const client = create(new URL('http://istart.work:1010'))
const client = create(new URL('http://127.0.0.1:1010'))
const { cid } = await client.add('Hello world!')

Related

How to access files uploaded to the public folder in Next.js?

I have a project in Next.js. I have that upload files and share that in public URL to this project.
With npm run dev first I uploaded files to public folder and it worked fine, but when I change to npm run start and upload files, the files upload to public folder but with URL http://mydomain/fileuploaded.jpg it did not show, is rare but it's there.
I searched on the Internet but I didn't find a solution for this problem.
From Next.js documentation:
Only assets that are in the public directory at build time will be served by Next.js. Files added at runtime won't be available.
You'll have to persist the uploaded files somewhere else if you want to have access to them in the app at run time.
Alternatively, you could setup your own custom server in Next.js, which would give you more control to serve static files/assets.
You can also achieve something similar using API routes instead. See Next.js serving static files that are not included in the build or source code for details.
a bit late but if someone need the same.
If your goal is to upload and get picture from your next server, you can instead of using the Next router, getting the image by yourself by create a route /api/images/[id] where [id] is your file name and you manually with fs send the picture back.
something like:
const file = await fs.readFile(`./uploads/image.png`)
console.log(file)
res.setHeader('Content-Type', 'image/png')
res.send(file)
Try and use nginx or another webserver to serve the public directory. That way it will serve newly added files without having to write extra code to serve files in nextjs.
server {
/images/ {
root /var/www/site/public
}
}

How to server a ".html" at certain URL in a Next.js app?

I have an ".html" file that I need to serve in a certain route in my Next.js app, like this ...
/pages/customr-route-name/my-html-file.html
So if I go to my website and type http://example.com/custom-route-name/my-html-file.html I can see it
How can I do that in Next.js?
This one requires an API route and a URL rewrite to get working. And the nice thing is, you'll be able to use this pattern for other things too (like if you want to generate an RSS feed or a sitemap.xml).
NOTE: You will need to be running Next 9.5 for this to work.
0. Move your HTML file (Optional)
Your file doesn't need to be located in the ./pages dir. Let's put it in ./static instead. Just replace your these route-file placeholders with your real filename later: ./static/<route>/<file>.html
1. Create the API route
Next lets you create API routes similar to how you would in an old-style host like Express. Any name is fine as long as it's in ./pages/api. We'll call it ./pages/api/static/<route>/<file>.js
// import
import fs from 'fs';
// vars
const filename = './static/<route>/<file>.html';
// export
export default async function api(req, res) {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.write(await fs.readFileSync(filename, 'utf-8'));
res.end();
}
2. Add a rewrite to next.config.js
In Next, rewrites work similar to their apache counterparts. They map a url location to a Next ./page.
// export
module.exports = {
rewrites: async () => [
{source: '/<route>/<file>', destination: './pages/api/static/<route>/<file>'},
],
};
3. Run it!
You should be able to test this with a regular next dev. Of course, changes to next.config.js require you to manually reboot the dev server.
If you look at the Next docs, you'll see you can use wildcards in both the API routes and these redirects, which might help with the direction you're going.
Update for NextJS Version 11
In your public folder you can create a folder structure patterned after the URL you want.
For example:
public/custom-path-folder-name/file.html
will be served at:
http://localhost:3000/custom-path-folder-name/file.html
For more information see the nextjs docs for static file serving

what is the proper way to do config lookups in react?

My React app currently uses my local API when making an axios.get() call with the following url:
http://localhost:3000/users
Instead of hard-coding the url, I need my component to do a lookup against the config file that is currently configured for the current environment. For example, when my API is running on Azure the axios get call should use the following url:
https://my-api.azurewebsites.net/users
What is the proper way to lookup this config value in a React app? For example, should I create some type of config.js file? What is the proper import/code for my component to hook into the config file for lookup?
Don't use dotenv, because this package was designed for server-side app - it injects config variables in the process.env dictionary, but the process global variable only exists in Node apps and is not available in the browser.
There are many other ways to do what you want, perhaps the simplest I can think of is to have a config file that exports values, and the values it exports depends on the environment the scripts runs in:
// config.js
const isProd = location.host === 'my-app.azurewebsites.net'; // or any other check
const devConfig = {
axiosBaseUrl = 'http://localhost:3000'
}
const prodConfig = {
axiosBaseUrl = 'https://my-app.azurewebsites.net'
}
export default isProd ? prodConfig : devConfig
// upon starting your app, before making any axios call
import config from './config';
const http = axios.create({
baseUrl: config.axiosBaseUrl
});
// use as such
http.get('/hello-world');
// locally: makes a call to http://localhost:3000/hello-world
// in production: makes a call to https://my-app.azurewebsites.net/hello-world
You can also have a config file which contents depends on the build environment, but that would be more complex to setup and is highly dependent on your build pipeline and there's no details about it in your question.
You can create a config file or can use environment variables.
For environment variables:
Create .env file in the root directory of your project.
Save your URL as REACT_APP_BASE_URL=http://localhost:3000/
Now you can access your base URL when you are making axios requests like this:
process.env.REACT_APP_BASE_URL

Uploading image files to AmazonS3 using ReactJs

I am fairly new to web development (currently enrolled in a bootcamp) and have struggled finding the needed resources to incorporate uploading to Amazon S3 in my project. I apologize for the vagueness ahead of time.
I currently have a react app that is pulling images from my AmazonS3 account but I am intending to give the user the ability to upload to my bucket and use/view the images on my website.
I have tried watching tutorials and looking at various GitHub Repo's to identify what I am missing but have been unable to locate a tutorial that involves React, JSX and Javascript. (I've seen jquery, PHP, etc). Ultimately, I know this task is difficult and I am willing to put in the work but felt the need to ask if anyone knows of a useful resource that can help me?
I've tried using the 'aws-nodejs-sample' repo, 'themetoerchef/uploading-with-react' repo, watched a youTube tutorial, I've looked into FineUploader and have read the react-S3-uploader npm files but am unable to connect the dots. Additionally, I've included my AWS access keys in my .env file and tried making query strings to access the S3 bucket.
Is there a better way to go about this or are there other ways to upload with react that may be useful outside of S3?
To upload to s3 from the browser you need to get a signedUrl from an aws sdk which is how aws verifies your identity. In my last application I used skd for nodejs to generate the signedUrl and pass it to my front end application to use in pushing files to s3. You don't have to go that route there is an sdk that can be used by javascript within the browser.
Check this aws link for more
Go to your project directory and run
npm install --save react-aws-s3
https://www.npmjs.com/package/react-aws-s3
And add the code in your component as per the NPM document
import S3 from 'react-aws-s3';
const config = {
bucketName: 'myBucket',
dirName: 'media', /* optional */
region: 'eu-west-1',
accessKeyId: 'JAJHAFJFHJDFJSDHFSDHFJKDSF',
secretAccessKey: 'jhsdf99845fd98qwed42ebdyeqwd-3r98f373f=qwrq3rfr3rf',
s3Url: 'https:/your-custom-s3-url.com/', /* optional */
}
const ReactS3Client = new S3(config);
/* Notice that if you don't provide a dirName, the file will be automatically uploaded to the root of your bucket */
/* This is optional */
const newFileName = 'test-file';
ReactS3Client
.uploadFile(file, newFileName)
.then(data => console.log(data))
.catch(err => console.error(err))
/**
* {
* Response: {
* bucket: "myBucket",
* key: "image/test-image.jpg",
* location: "https://myBucket.s3.amazonaws.com/media/test-file.jpg"
* }
* }
*/
});
Now its everything is done, make sure to load your keys and secrets from Process ENV.
NOTE: Please don't forget to add the CORS policy on the AWS bucket if you see corse error, see here the detailed example.
thanks

how can I enable the user download the whole application from the client side?

So, I have a web app hosted in heroku which is automatically updated when I update my github repository. I want to enable the user to download the all the app files with their folders, images etc as a zip from the client side so he can run it offline locally. I also want to add a file with user's comments to that zip before I force it to be downloaded on his browser.
I found a way to do it by redirecting him to github (but this will actually not redirect him there, it will just force a zip from github to be downloaded) :
window.location.replace("https://github.com/foo/FOO/archive/master.zip");
But this solution doesn't work for me because I want to add to that zip an other file which will be created at the moment of the user download request.
Does anyone have a solution to this?
Is there a way to do that by making requests to herokku to receive the files and using the jszip to pack them?
I found the solution using github's service, JSZipUtils and jszip. Here's the code for whom it might of help :
var content = null;
JSZipUtils.getBinaryContent("https://github.com/foo/FOO/archive/master.zip", function(err, data) {
if(err) {
throw err; // or handle err
}
var zip = new JSZip(data);
// to remove a not needed file
zip.remove("CWAPP-master/abc.js");
// to add a custom file
zip.file('CWAPP-master/myClientSideFile.js',file);
content = zip.generate({type:"blob"});
saveAs(content, 'myZip'); // force download
});

Resources