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

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
}
}

Related

Removing the need for pathing in cloudFront distribution of S3 bucket requiring .html at the end of the page name, in Next.js project

I have a Next.js, React, Ts project that exists on a S3 bucket as a static site and is distributed via cloudFront.
The problem I'm running into is for me to go a different page I have to append .html at the end of the page name.
So mysite.com/profile will return a <Code>NoSuchKey</Code> error, however mysite.com/profile.html will route me correctly.
Is there some way to remove this necessity?
If this is a next issue i'm using
npx next build
npx next export
To build and export the /out directory which I then upload to my S3 bucket
my next.config.js
module.exports = {
target: "serverless"
}
I had it like this as I was originally making use of serverless for Next but have since moved away from it as I'm largely making use of client-side rendering and don't need any of the features it was providing and I am still in the process of doing a cleanup on the project.
Routing in S3 is done with exact match of the file name. You can remove .html extension to use routing as you like. And set metadata Content-type to text/html, to view it properly in browser

Google Cloud Bucket and ReactJS app Access

Using ReactJS I made a Build (reactJs static, npm build) and uploaded it to Google Cloud Storage Bucket, but getting a issue with the Path and Build folder files. The app (/static website) running but could not fetch the files from the bucket directory for eg the index.html & logo. (404 or 403 error )
Structure: Parent Bucket > Build folder (index.html, static folder & other files inside Build)
Any one have any suggestion on this. How to resolve this?
Do I need to create an app.yaml for GCS Bucket or any alternative?
I have gone through the article quite similar but for AppEngine instead of Bucket. https://medium.com/google-cloud/how-to-deploy-a-static-react-site-to-google-cloud-platform-55ff0bd0f509.
I have tried with app.yaml file but does not work for me.
I had exactly the same issue as mentioned by the OP. I am sharing my version of solution just in case anyone else ends up here.
As shown in the screenshots by OP, the 403 errors showed up for me because the URL of the static files in build/static folder was not correctly configured by the react-scripts build script.
Eg:
The url for index.html file was https://storage.googleapis.com/{bucket-name}/index.html.
However, when the page loaded, it requested files having url https://storage.googleapis.com/static/js/main.f555c3e0.chunk.js. It should rather be
https://storage.googleapis.com/{bucket-name}/static/js/main.f555c3e0.chunk.js
This is happening because by default react-scripts build assumes that your files will be served from root folder of your host.
To fix this add the following field in package.json of your project
"homepage": "https://storage.googleapis.com/{bucket-name}"
This tells the build script that it needs to add a relative path for serving static files.
For details please refer: https://create-react-app.dev/docs/deployment/#building-for-relative-paths
In order to set the routes of a static website stored in Google Cloud Storage, you need to assign a suffix to your objects. In other words, using suffixes is the intended way to configure your website. You can see more information in Hosting a static website document.
For your main index page you should set MainPageSuffix and for the not found page 404.html you should set NotFoundPage as suffix.
You can see more information on how to configure your static web here

react-create-app prod html from public folder not found for an iframe

I have a create-react-app that needs to embed an html file (along with its own JS and other files) into an iframe on one of the components. I've searched the Facebook react docs on public folder (which says it should work), various other stack overflow questions to no avail.
I added the folder ixoearth containing the external files into public folder. Folder structure
When I access it in dev mode (localhost:3000), or in prod mode from the network IP it works (eg. 192.168.1.128:63738 ). but as soon as I attempt localhost production mode it doesn't find any of the files in the public folder.
Here's my iframe URL:
iframe src
When using create-react-app you need to use a special PUBLIC_URL variable like is mentioned in the docs. This will generate the right path during the build phase so that it works in production.

laravel 5.4 image 404 error

I am uploading images to my applications storage/app/public/avatars directory. The files are uploading and are there in this folder - i have checked it. And loading the page shows the image as long as i am in my local pc. Then i moved the project to a shared hosting. Since then the images are not loading. From chrome console network tab i can see for the images laravel is throwing 404 error.
Here is what i have tried:
On the remote machine i recreated the symbolic link in my public folder as storage that is pointing to the storage/app/public folder.
Tried to copy and paste the image src directly into the browser - getting NotFoundException in RouteCollection.php
Cleared views, cache, config cache
Spent 5 hours trying to figure it out. Works fine on local pc. Just not on the shared hosting.
Desperately seeking help :(
After a bad night sleep of 4 hours i started again and found the problem. Very novice mistake, but can be ver hard to locate.
Here is what it is. I uploaded my laravel project folder to a shared hosting. Say my project name is myproject. This folder is at the same level as the public_html folder. Then i copied the contents of the myproject/public folder to the public_html folder.
As you know, you are supposed to create the symbolic link inside your public directory and the link should point to the storage/app/public directory (if you are using the public disk driver for your file storage). I did create the symbolic link inside the public folder, but at the wrong public folder. Since i copied the contents of public folder to the public_html folder, i should have created the symbolic link inside the public_html folder, not inside myproject/public folder!!
----public_html
---css
---js
---(other files etc. etc)
---storage <= this is where the symbolic link should be
----myproject
---public
---css
---js
---(other files etc. etc)
---storage <= not here!!
Very stupid of me.
btw, below is a tutorial of how to transfer a local laravel project to a shared hosting:
guide to deploy laravel 5 app on shared hosting

Angular JS + Laravel 4: How to compile for production mode?

So i have watched the 5 part youtube videos by David Mosher about Angular JS (vids great by the way). In the part 2 (http://www.youtube.com/watch?v=hqAyiqUs93c), it has a practical mysql database usage which I almost wanted.
I'm going to use AngularJS along with Laravel 4, but I had no idea which files I'm going to upload for the web hosting later. I'm trying to run the web app under "/public" folder in my root on localhost (localhost/public/) but the css and js points to the wrong directory (points to the root: '/css/style.css').
Another method I have tried is by copying all the files to the root and moved all files inside "public" to root. Then I navigate to "localhost/public/". All works fine in script paths, except that it doesn't seemed to do any connection to the database (either the laravel or angular failed).
Is there any proper way to do this for practical use (without using php artisan serve or grunt run or lineman run on the server)? Which files I should upload later?
EDIT: the reason is my web hosting doesn't allow me to install nginx or run code remotely using putty, so I need a manual way to do this. Thanks.
First install latest laravel in your localhost. See doc.
Assuming you have completed composer install command.
Then move your all public folder contents to the project root.
Next change the line 21 in index.php from,
require __DIR__.'/../bootstrap/autoload.php';
to
require __DIR__.'/bootstrap/autoload.php';
and line 35 content
$app = require_once __DIR__.'/../bootstrap/start.php';
to
$app = require_once __DIR__.'/bootstrap/start.php';
Now you can access project without public folder.
Place your css, js and other assets folder in root like http://localhost/laravel/css
Note that the laravel blade and angular also using {{ syntax for compilation.So you need to change the laravel blade syntax to {= and =}.Otherwise you will get conflict.
To do this open vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php file and change line 45 to this
protected $contentTags = array('{=', '=}');
and line 52 to this
protected $escapedTags = array('{={', '}=}');
Now you can use {{ for angular and {= for blade.
For linking your assets, use HTMLBuilder functions, see doc here.
Now use these in blade,
{= HTML::style('css/style.css') =} // links localhost/project/css/style.css
{= HTML::script('js/jquery.js') =}
Use migrations and db seeds in localhost and make an exported copy of db for online hosting
After completing project, copy entire project content to online server and change db configuration and import database.
Directory Structure for Online
There will be a public directory for your file hosting, where you put your files in web root.
That may be htdocs or public_html and now it's your project public root.Now the directory structure will be,
-- app
-- bootstrap
-- css
-- images
-- js
-- vendor

Resources