0

I am trying to load a file from a folder using a name from react props.

when I write this:

import FileImage from '!!file-loader!../public/uploads/file-1589134024728.file';

<img src={FileImage}/>

everything works (but is static). In elements I see:

<img src="368d70b7855164f45e8b1c68db4d549c.file">

[![working][1]][1]

But using this:

src={`!!file-loader!../public/uploads/${file}`}

will show as

<img src="!!file-loader!../public/uploads/file-1589134024728.file">

[![not working][2]][2]

GET http://localhost:8080/public/uploads/file-1589134024728.file 404 (Not Found)

I also tried

src={`../public/uploads/${file}`}

while webpack.config.js looks like that:

            {
                test: /\.(woff(2)?|ttf|eot|svg|file)(\?v=\d+\.\d+\.\d+)?$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                            outputPath: 'fonts/'
                        }
                    }
                ]
            }```

I believe I somehow need to return [contenthash].[ext] but how?

  [1]: https://i.stack.imgur.com/ZDx6l.png
  [2]: https://i.stack.imgur.com/lCnMd.png

1 Answers1

0

These files look like they are uploaded, which means you don't have access to their names at build time. This is ok, you have the file name.

You need to make sure that the /uploads/ directory is available through your HTTP server, and then you can use src={'/uploads/' + file} to load the resource from that location.

Even if these are not user uploads, but static files that you provide, then you can put them in your public/uploads directory and still just link them using their location on the webserver. It's hard to be sure without knowing where file comes from.

jens
  • 2,075
  • 10
  • 15
  • the file is uploaded to the server by a user, saved to /public/uploads with unique identifier name, and the name of the file is saved to mongo db. Then I get the name of the file and search for it in /public/uploads – Networking pup May 13 '20 at 15:47
  • Yes so you wont be using your build pipeline for these assets. Simply loading their source with “User assuming files is a path to a file in your public folder. – jens May 13 '20 at 16:33