使用 multer 存储上传文件链接的正确方法是什么?

What is proper way to store links of uploaded files using multer?

使用 multer 上传多个文件后,它为我提供了每个文件的路径,如:

"photo" : [ 
        "public/uploads/1/store/aa17c810-0178-11ea-adf6-c9fa892f6902.png",
...
    ],

并且可以在 url、“http://localhost:3000/public/uploads/1/store/aa17c810-0178-11ea-adf6-c9fa892f6902.png”中访问。

但在 React(或任何前端)中,我必须在 url 前面加上斜线,如下所示(假设 imageUrl 的值为 "public/uploads/1/store/aa17c810-0178-11ea-adf6-c9fa892f6902.png":

<div>
       <img src={"/" + imageUrl} />
 </div>

如果我不在前面加上“/”,路径就是相对路径。

如果我使用那个 imageUrl 而没有将“/”附加到那个 img src 的头部,问题是在页面 url 中 http://localhost:3000/product, it will try to check the path relatively and then get the file from "http://localhost:3000/product/public/uploads/1/store/aa17c810-0178-11ea-adf6-c9fa892f6902.png”,文件不存在.

所以我的问题是,我是否应该将“/”添加到多个 returns 的每个文件路径,然后将其存储到 mongodb?

还是我每次使用 img 标签时都应该加上“/”?

最标准的首选方式是什么?

当我使用 multer 时,我也得到了这些 problems.I 认为在你的情况下,只需在 mongodb

的每个路径中存储/使用 multer

我会保存整个路径,包括 MongoDB 中的第一个斜杠,因为以“/”开头的路径有点表示它从根开始。 (在这种情况下,您的项目的根目录。)

此外,使用它的潜在性能提升:

<div>
    <img src={imageUrl} />
</div>

而不是:

<div>
    <img src={ "/" + imageUrl} />
</div>

如果不是不存在的话可以忽略不计,但是代码看起来稍微干净一些。