简体   繁体   English

如何在 React 应用程序中获取根文件夹之外的文件的路径

[英]How to get the path to a file outside the root folder in React application

This is simplified folder structure in my React application created with the create-react-app.这是我使用 create-react-app 创建的 React 应用程序中的简化文件夹结构。 For the back-end I'm using the Express framework.对于后端,我使用的是 Express 框架。

└── ReactApp/
    ├── client/
    |  ├── node_modules/
    |  ├── public/
    |  └── src/
    |      └── components/
    |         └── component.js
    └── server/
       ├── index.js
       └── Uploads/
           └── file.txt

Inside component.js file I want to define the path to the file.txt file located to the server/Uploads folder.component.js文件中,我想定义位于server/Uploads文件夹的file.txt文件的路径。

 handleClick() {
        const pathToFile = '../../server/Uploads/file.txt;
        this.setState({ input: pathToFile})
  }

The issue is that this defined path cannot locate the txt file inside the Uploads folder.问题是这个定义的路径无法在 Uploads 文件夹中找到 txt 文件。

Try:尝试:

handleClick() {
   const pathToFile = '../../../server/Uploads/file.txt';
   this.setState({ input: pathToFile})
}

The solution is to configure ExpressJS to serve static files inside the Uploads folder.解决方案是将 ExpressJS 配置为在 Uploads 文件夹中提供 static 文件。

index.js index.js

app.use(express.static('Uploads'));

and then change the path inside the component.js file.然后更改component.js文件中的路径。

handleClick() {
    const pathToFile = 'file.txt';
    this.setState({ input: pathToFile})
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM