图像未渲染 - 不允许加载本地资源:

问题描述 投票:0回答:1

我正在尝试渲染图像,但它显示不允许加载本地资源:

这是我的代码:

fileUpload.js

const multer = require("multer");
const path = require("path");

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.resolve("./public/upload"));
  },
  filename: function (req, file, cb) {
    const fileName = `${Date.now()}-${file.originalname}`;
    cb(null, fileName);
  },
});

module.exports = { storage }; 

postsController.js

exports.createPost = asyncHandler(async (req, res) => {
  try {
    const userFound = await User.findById(req.userAuth._id);
    if (!userFound) {
      throw new Error("User Not found");
    }

    const { title, content, categoryId } = req.body;

    const postFound = await Post.findOne({ title });

    if (postFound) {
      throw new Error("Post already exists");
    }

    const post = await Post.create({
      title,
      content,
      category: categoryId,
      author: req?.userAuth?._id,
      image: req?.file?.path, 
    });

    console.log('This is Image Path req file',req.file.path);// Log this Whole Path:-  C:\Users\rahul\Desktop\Github Final Project\backend\public\upload\1710572384640-solid black.jpg

    await User.findByIdAndUpdate(
      req?.userAuth?._id,
      {
        $push: { posts: post._id },
      },
      {
        new: true,
      }
    );

    await Category.findByIdAndUpdate(
      req?.userAuth?._id,
      {
        $push: { posts: post._id },
      },
      {
        new: true,
      }
    );

    res.json({
      status: "success",
      message: "Post Successfully created",
      post,
    });
  } catch (error) {
    console.log("Final Error From controller", error);
    res.status(400).json({
      status: "error",
      message: error.message,
    });
  }
});

postRouter.js

postsRouter.post("/", isLoggin, upload.single("file"), createPost);

userPosts.js


        <div className="flex flex-wrap mb-12 -mx-4 md:mb-20">
          {posts?.map((post) => {

            return (
              <>
                <div className="w-full px-4 mb-8 md:w-1/2">
                  <a className="block mb-6 overflow-hidden rounded-md" href="#">
                    <img
                      className="w-full"
                      src={`./public/upload/${post?.image}`}
                      alt={post?.tile}
                    />
                  </a>
                  <div className="mb-4">
                    <a
                      className="inline-block px-3 py-1 text-xs font-medium leading-5 text-green-500 uppercase bg-green-100 rounded-full shadow-sm hover:text-green-600 hover:bg-green-200"
                      href="#"
                    >
                      {post?.category?.name}
                    </a>
                    {/* Schedule post link */}
                    <Link
                      to={`/posts/schedule/${post?._id}`}
                      className="flex w-1/2 items-center px-6 py-1 bg-blue-500 text-white rounded-md shadow-md hover:bg-blue-700 transition-colors duration-300 ease-in-out"
                    >
                      <FiCalendar className="mr-2" /> Schedule Post
                    </Link>
                  </div>
                  <p className="mb-2 font-medium text-coolGray-500">
                    {new Date(post?.createdAt).toDateString()}
                  </p>
                  <a
                    className="inline-block mb-4 text-2xl font-bold leading-tight md:text-3xl text-coolGray-800 hover:text-coolGray-900 hover:underline"
                    href="#"
                  >
                    {post?.title}
                  </a>
                  <p className="mb-6 text-lg font-medium text-coolGray-500">
                    {post?.content}
                  </p>
                </div>
              </>
            );
          })}
        </div>

项目结构 Backend Frontend

那么为什么我的图像没有渲染并通过整个渲染 我还从静态内容进行服务器

app.use(express.static(path.join(__dirname, "public")));
,但静态图像未渲染。

我也尝试像这样从 api 渲染图像,但仍然不起作用。

<img
  className="w-full"
  src={`http://localhost:9080/api/v1/posts/${post?.image}`}
  alt={post?.tile}
/>

Image Rendering

reactjs react-redux mern multer react-fullstack
1个回答
0
投票

问题在于您在

destination
方法中提供文件目标文件夹的方式:您使用的是绝对路径,而不是相对于项目文件夹的路径,此处:

cb(null, path.resolve("./public/upload"));

然后像这样保存,然后前端尝试从文件系统加载它,然后你会得到错误。

因此,尝试更改代码以使用

destination
方法中相对于项目文件夹的路径:

cb(null, "./public/upload");

图像路径现在应为

public\upload\1710572384640-solid black.jpg

因此,更改模板属性中的

src
以仅使用数据库中的路径:

src={ post?.image }

但是,这不会显示,因为这里:

app.use(express.static(path.join(__dirname, "public")));

它将

public
文件夹安装在
/
路径上,因此图像的路径实际上是
upload\1710572384640-solid black.jpg

因此,您可以从图像路径字符串中删除

public
部分,例如如下所示:

src={ post?.image.replace('public', '') }

但是最好重构存储库,并将上传文件夹从公共文件夹中移动为单独的文件夹,以避免与公共混合并更好地处理,然后您可以将其公开(或创建单独的路由,添加身份验证)中间件等)

例如,您可以将

upload
设为单独的文件夹,并将其公开:

app.use('/', [express.static('public'), express.static('upload')]);

并保存,然后仅使用文件名从公共上传文件夹提供文件(路径中没有

upload
部分):

// now you can use just filename: 1710572384640-solid black.jpg`

src={ post?.filename }
© www.soinside.com 2019 - 2024. All rights reserved.