【问题标题】:Next.js: Importing images into a componentNext.js:将图像导入组件
【发布时间】:2020-09-26 15:39:06
【问题描述】:

我正在使用"next": "^9.4.4", 并且有:"next-images": "^1.4.0", "next-optimized-images": "^2.6.1",

这是我的next-config.js

const withCSS = require('@zeit/next-css');
const withSass = require('@zeit/next-sass');
const withImages = require('next-images');
const optimizedImages = require('next-optimized-images');

module.exports = withImages(
  optimizedImages(
    withCSS(
      withSass({
        target: 'serverless',
        env: {
          MAPBOX_ACCESS_TOKEN:
            'TK421'
        },

        webpack(config, options) {
          config.module.rules.push({
            test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
            use: {
              loader: 'url-loader',
              options: {
                limit: 100000,
                target: 'serverless'
              }
            }
          });

          return config;
        }
      })
    )
  )
);

但在我的组件中,我得到了一个损坏的图片链接,这是我的组件:

import { useState, useEffect } from 'react';

import { Card, Icon, Image, Segment, Form } from 'semantic-ui-react';

import axios from 'axios';


function ImageUploader({ userAvatar }) {
  var [userAvatar, setUserAvatar] = useState(userAvatar);


  useEffect(() => {
    setUserAvatar(userAvatar);
  }, [userAvatar]);

  function fileUploader(e) {
    console.log('event fileUploader ', e);
    var imageFormObj = new FormData();

    console.log('e.target.files[0] ', e.target.files[0]);

    imageFormObj.append('imageName', 'multer-image-' + Date.now());
    imageFormObj.append('imageData', e.target.files[0]);
    setUserAvatar(window.URL.createObjectURL(e.target.files[0]));

    console.log('userAvatar ', userAvatar);
    console.log('imageFormObj ', imageFormObj);

    axios
      .post(`/users/uploadmulter`, imageFormObj)
      .then(data => {
        if (data.data.success) {
          alert('Image has been successfully uploaded using multer');
        }
      })
      .catch(err => {
        alert('Error while uploading image using multer');
      });
  }

  return (
    <>
          <Image
            src={require('../../public/static/uploads/profile-avatars/placeholder.jpg')}
            alt="user-avatar"
          />
    </>
  );
}

我也很困惑,因为在文档中似乎表明 box 支持静态文件/图像...

静态文件服务 Next.js 可以在根目录中名为 public 的文件夹下提供静态文件,如图像。然后,您的代码可以从基本 URL (/) 开始引用 public 中的文件。

例如,如果您将图像添加到 public/my-image.png,以下代码将访问该图像:

我已经按照他们的建议进行了尝试:

&lt;Image src="/uploads/profile-avatars/placeholder.jpg" alt="user-avatar" /&gt;

有趣的是,我在浏览器中没有收到404

任何帮助将不胜感激!

【问题讨论】:

    标签: image next.js next-images


    【解决方案1】:

    您的图像必须位于保留名称为 public 的文件夹中。然后盒子里的报价就会起作用。

    【讨论】:

      猜你喜欢
      • 2020-06-07
      • 2019-10-10
      • 2021-02-20
      • 1970-01-01
      • 2021-09-01
      • 2021-01-05
      • 2022-12-04
      • 2021-08-05
      • 2021-11-15
      相关资源
      最近更新 更多