View/Download Pdf Files in React - Router 4

我的梦境 提交于 2019-12-21 17:28:57

问题


I have a set of pdf files sitting in a folder in my project.

All I need to do is to create a link to these PDF files and view them in browser or download it.

I use React Router 4 and React 16 and create-react-app bootstrapping tool.

Regardless of how I link it (Link component or a tag) it still goes to my last Route in my router config.

I have been googling for last two hours... But no luck..

Is there any way to tell router not to route for PDF/XLS files?

Thanks


回答1:


I met the same issue, I think it's because of the way CRA handles queries : I ended up putting my PDF files in the public folder, and link to them using :

{process.env.PUBLIC_URL + '/myfile.pdf'}

as src to my tags.

Not the best way I guess, but works fine enough...




回答2:


I tried squizz's way, but the problem I'm finding is that if you click the link more than once or twice, it will revert to going back to going to the last route.

You can make a folder in src to hold your pdf's, and link to them normally, ex:

import pdf from '../files/myfile.pdf'
render () {
    <a href={pdf}>Click here for my pdf</a>
}

The only problem is, you will get a hash appended to your file, so it will come out as myfile.d2e24234.pdf or something. I think it has to do with file-loader...currently trying to figure it out.

EDIT

The answer if you don't want to use src is to delete the service worker from the create-react-app project. For some reason it affects react-router's handling of server routes.

I made a github issue here to read about it: https://github.com/facebookincubator/create-react-app/issues/3608




回答3:


Ran into this same issue and fixed it by resorting to old-fashioned html:

<a href="docs/document.pdf">
  Document
</a>

And copying the pdf to my publicly served folder with CopyWebpackPlugin in webpack.config:

plugins: [
    new CopyWebpackPlugin([
      {
        from: 'docs/document.pdf',
        to: path.resolve(BUILD_PATH + "/docs/document.pdf")
      },
    ])
]



回答4:


This worked for me:

<Link
    to="route"
    onClick={(event) => { event.preventDefault(); window.open(filePath); }}>
        Click to download
</Link>


来源:https://stackoverflow.com/questions/47718289/view-download-pdf-files-in-react-router-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!