我在尝试将 pdf 文件从我的 React 应用程序下载到我的 table 面时遇到困难。我之前已经发布了问题,并在此处找到了详细信息 How to download pdf file with React .现在我收到了一个答案,但实现了它,随后的建议也变得平淡无奇。但是我认为还没有看到这个问题的人可能会帮助我,因为我很难解决这个问题。就这样吧。
我有一个具有以下树结构的 React 应用程序:
app
|
|- Readme.md
|- index.html
|- node_modules
|- package.json
|- resume.pdf -------> This is the file I want downloaded
|- src
|
|-App.css
|- App.js
|- App.test.js
|- favicon.ico
|- index.css
|- index.js
|- assets
|-modules
|-skills.js -----> Here is where I reference it.
这是我的 skills.js
的一部分我在哪里引用 <a>
链接:
class Skills extends Component {
render() {
return (
<div>
<ReactHighcharts neverReflow={true} config={highchartConfig} domProps={{id: 'chartId'}}></ReactHighcharts>
<a href="resume.pdf" download="resume.pdf">Click to Download My Resume</a>
</div>
);
}
}
当我点击 Chrome 上的按钮时,我得到一个 Failed - No File
错误。我被告知要有这样的目录结构,并在 <a>
中引用 pdf 文档。链接。
当我尝试点击链接时 localhost:3000/resume.pdf
在控制台中我看到这个错误 browser.js:49 Warning: [react-router] Location "/resume.pdf" did not match any routes
当我在 Firefox 中尝试同样的事情并下载它时,firefox 说
The file resume.pdf could not be opened. It may be damaged or use a file format that Preview doesn't recognize.
我真的需要一些帮助。我不确定为什么我根本无法下载此 pdf。有谁知道可能是什么问题?
最佳答案
我认为有几种方法可以解决这个问题...
1。将路径添加到您的服务器。
假设您使用的是 Express,请添加静态路径。然后,您需要在应用程序根目录中创建一个 public
文件夹,并将文件放入其中。
// add static path
app.use(express.static(path.join('public')));
从技术上讲,您也可以手动定义路线。
app.get('resume.pdf',(req, res) => {
res.sendFile('/resume.pdf')
})
2。网页包
如果您使用 Webpack 来捆绑您的应用程序,您可以添加一个加载程序来处理 pdf 文件并使其在最终 bundle 中可用。这与需要 JS 模块然后将其包含在构建中的方式相同。
$ npm install --save file-loader
// add the loader to webpack.config.js
...
loaders: {
{
test: /\.pdf$/,
loader: 'file?name=[name].[ext]'
}
...
}
然后,在您的组件中需要文件而不是引用路径。
<a href={require(../relativeToDirectory/resume.pdf)} download="resume.pdf">Click to Download My Resume</a>
(请注意,我对这个最没信心,因为我使用它是一个不同的用例,因为我使用最终的构建文件夹,将其压缩并上传到我的服务器。它可能只有在服务器已经在处理静态路径)。还有 url-loader
,它将文件转换为 base64 字符串并将其嵌入到 url 中……它可以代替 file-loader
。
关于javascript - 无法使用 react 和 href 元素在本地主机中下载 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40667630/