如何在Laravel的“app”文件夹之外的文件夹内创建文件的路径?

How can i create a path to files inside folders that are outside of "app" folder in Laravel?

提问人:jpesa 提问时间:8/24/2023 最后编辑:jpesa 更新时间:8/30/2023 访问量:60

问:

例如,这是我的文件结构:

  • 我的项目
    • 应用程序
    • 启动
    • 配置
    • 数据库
    • node_modules
      • pdfjs-dist
          • PDF格式.js
    • 公共
      • 上传
        • 文件
          • solution_12.pdf
    • 资源

因此,当我在网络浏览器中输入 http://127.0.0.1:8000/uploads/documents/solution_12.pdf (1) 时,它工作正常,网络浏览器显示 pdf 文件。但是当我输入 http://127.0.0.1:8000/node_modules/pdfjs-dist/build/pdf.js (2) 时,我得到未找到错误。 那么有人可以向我解释一下 laravel 中的路径是如何工作的吗?为什么 (1) 链接不包含“公共”路由(upload/documents/solution_12.pdf存储在公共文件夹中)但它仍然有效?为什么找不到 (2) 链接返回?

PHP Laravel 文件 URL

评论

1赞 Maksim 8/24/2023
你不需要在运行时访问node_modules - 使用 mix 或 vite 来编译你的 js。
0赞 jpesa 8/24/2023
嗯,我需要路径,这样我就可以设置pdfjsLib.GlobalWorkerOptions.workerSrc
2赞 kris gjika 8/24/2023
您的网络服务器将您的域名指向您的文件夹,它之外的任何内容都无法作为您的网络浏览器的文件访问/public
1赞 Maksim 8/24/2023
你可以这样做 - 在 boostrap 中导入你的库,用 mix/vite 编译 js 并做任何你想做的事情。在文档中阅读编译器的工作原理。

答:

3赞 Shailesh Matariya 8/24/2023 #1

Laravel从public/index.php文件提供整个应用程序,这意味着当您在服务器/云上运行或托管时,您必须将域根指向。因此,服务器可以访问文件夹中的所有文件。如果要从 访问文件,则必须将文件路径添加到 OR 配置中,然后将它们复制/编译到 PUBLIC 文件夹中。php artisan serve/publicpublicnode_moduleslaravel mixvite

对于最佳做法,应将文件上传到文件夹中,您可以通过执行命令将其符号链接到该文件夹。storagepublicphp artisan storage:link

0赞 jpesa 8/29/2023 #2

谢谢你的回答。你能告诉我更多关于vite部分的信息吗?我做了一些研究,这就是我所做的:

在 vite.config.js 中,在 defineConfig 中:

plugins: [
        laravel({
            input:
                [
                    'node_modules/pdfjs-dist/build/pdf.js'
                ],
            refresh: true,
        }),
    ],

在 app.js 中,我导入 pdf.js 脚本:

import '../../node_modules/pdfjs-dist/build/pdf.js';

要使用此脚本,请在我的资源/视图/讲师/课程/编辑.blade.php 我补充:

<script src="node_modules/pdfjs-dist/build/pdf.js"></script>

但是控制台说找不到我的pdfjsLib。我做错了什么?

评论

0赞 Shailesh Matariya 8/29/2023
请使用这个 vite 插件从节点模块复制文件: npmjs.com/package/vite-plugin-static-copy Ref: laracasts.com/discuss/channels/vite/copying-assets-with-vite
0赞 jpesa 8/30/2023 #3

关于 vite 插件,还有其他步骤需要继续吗?因为我在我的vite.config.js中添加了这个:

plugins: [
        viteStaticCopy({
            targets: [
                {
                    src: 'node_modules/pdfjs-dist/build/pdf.js',
                    dest: 'js/pdf.js'
                },
            ]
        }),
    ]

然后运行 npm dev build,但我仍然收到错误。我错过了什么吗?