无法在React中使用Webpack和url-loader / file-loader来查看(在后端服务器上)上传的图像

我正在研究FileUploader(现在为Images),它将使用户能够一次将多个文件上传到后端服务器。

我具有以下设置

  1. 配置了url-loader的Webpack支持各种图像。
  2. 我有一个React客户端,在名为client的单独目录中的9002端口上运行。它具有一个名为“ UploadDocumentsContainer”的组件。该组件将允许用户选择多个输入文件进行上传。该组件在端点“ / uploads”对后端服务器进行axios调用。
  3. 后端节点服务器正在运行一个目录,然后客户端目录在端口9001上运行。它具有配置为迎合上载图像的上载端点。服务器将图像移至/ client / public / uploads,并将响应连同图像的fileName和filePath发送回客户端。
  4. React客户端还具有一个名为ProgressFileUpload的单独组件,一旦上传从0开始到100%(取决于上传状态),该组件就会启动。

到目前为止的问题如下。

  1. 图像已成功上传到服务器,我们从服务器获得200响应,其中包含图像的文件名和文件路径。
  2. 但是在使用DisplayFile组件渲染相同的上传图像期间,应用程序崩溃并出现以下错误。

自最近三天以来,我一直在努力使其正常运转。我经历了很多github和stackoverflow帖子,但没有找到相同的解决方案。如果能在同一页面上获得一些输入/反馈/解决方案,我将不胜感激。

我的猜测是,我的Webpack.configs(publicPath或url-loader)出了点问题,或者在捆绑后图像的filePath没有指向正确的方向。

上述错误发生在组件中: 在DisplayFile中(由UploadDocumentsContainer创建) 形式(由UploadDocumentsContainer创建) 在div中(由UploadDocumentsContainer创建) 在div中(由UploadDocumentsContainer创建) 在div中(由UploadDocumentsContainer创建) 在UploadDocumentsContainer

Error: Cannot find module './wallpaper-1680x1050.jpg' bundle.js line 96 > eval:14:11
TypeError: _context.t0.response is undefined

沙盒链接引发错误“请求失败,状态码为422”

GITHUB链接:-https://github.com/aryan21710/FileUploader.git

Webpack.config.js:-

const path = require("path");
const webpack = require("webpack");
const dotenv=require("dotenv");


module.exports = () => {
     // call dotenv and it will return an Object with a parsed key 


  return {
    mode: "development",// babel-polyfill allows us to use all the latest es7 javascript features like Array.includes,Array.from and so on
    // 
    entry: ["babel-polyfill",path.join(__dirname,"client/src/app.js")],devserver: {
      proxy: {
        "/client/public/uploads/": "http://localhost:9001"
      },// index.html will be inside build and not dist after installing htmlWebpackPlugin.
      contentBase: path.join(__dirname,"client","public","build"),hot: false,inline: true,historyApiFallback: true,watchContentBase: true,port: 9002,watchOptions: {
        ignored: [
          path.resolve(__dirname,"fileUploadServer/server.js"),path.resolve(__dirname,"node_modules/")
        ]
      }
    },output: {
      path: path.join(__dirname,// Will generate a new bundle.js with name "main.somerandomhash.bundle.js" every time when app changes.
      filename: "bundle.js",},module: {
      rules: [
        {
          loader: "babel-loader",test: /\.js$/,exclude: /node_modules/
        },{
          test: /\.s?css$/,use: ["style-loader","css-loader","sass-loader"]
        },{
          test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg|jpg)$/,loader: "url-loader",}
      ]
    },devtool: "cheap-module-eval-source-map"
  };
};

UploadDocumentsContainer.js:-

import React,{ useState } from "react";
import { useHistory } from "react-router-dom";
import axios from "axios";
import ProgressFileUpload from "./ProgressFileUpload";

const UploadDocumentsContainer = () => {
  const [selectedFile,setSelectedFile] = useState("Choose File");
  const [displayFile,setDisplayFile] = useState([]);
  const [file,setfile] = useState([]);
  const [uploadPercentage,setUploadPercentage] = useState(0);





  const onChangeFile = event => {
    console.log("event.target.files",event.target.files[0]);

    for (let i = 0; i < event.target.files.length; i++) {
      let _ = event.target.files[i];
      setfile(file => [...file,_]);
    }
    event.target.files.length > 1
      ? setSelectedFile(`${event.target.files.length} Files`)
      : setSelectedFile(event.target.files[0].name);
  };

  const onUpload = async e => {
    e.preventDefault();
    console.log("file",file);
    console.log("selectedFile",selectedFile);
    const formData = new FormData();
    file.forEach(_ => {
      console.log("_",_);
      formData.append("file",_);
    });
    console.log("FORMDATA INSIDE UploadDocumentsContainer",formData);

    try {
      const response = await axios.post(
        "http://localhost:9001/client/public/uploads",formData,{
          headers: {
            "access-control-allow-origin": "*","Content-type": "multipart/form-data"
          },onUploadProgress: progressEvent => {
            setUploadPercentage(
              parseInt(
                Math.round((progressEvent.loaded * 100) / progressEvent.total)
              )
            );

            // Clear percentage
            setTimeout(() => setUploadPercentage(0),10000);
          }
        }
      );

      let { fileName,filePath } = response.data;
      console.log("response.data",response.data);
      fileName = fileName.split(",");
      filePath = filePath.split(",");
      console.log("fileName",fileName);
      console.log("filePath",filePath);

      setDisplayFile(displayFile => [...displayFile,...fileName]);
      console.log(
        "displayFile from the server",displayFile,":",displayFile.length
      );
      console.log("response back from server:-",fileName," AND ",filePath);

      // const importAll = r => {
      //   return r.keys().map(r);
      // };

      // setImages(
      //   importAll(
      //     require.context(
      //       "./../../../../../../../public/uploads/",//       false,//       /\.(png|jpeg|svg|jpg)$/
      //     )
      //   )
      // );
    } catch (error) {
      if (error.response.status == 500) {
        console.log("There was a problem with the server");
      } else {
        console.log(error.response.data.msg);
      }
    }
  };

  const DisplayFile = () => {
    console.log("displayFile",displayFile);
    console.log("uploadPercentage",uploadPercentage);
    return (
      <div classname="displayFileContainer">
        {displayFile.length > 0
          ? displayFile.map((_,idx) => {
              const myimg = require(`./../../../../../../../public/uploads/${_}`)
                .default;
              console.log("myimg",myimg);
              return (
                <div classname="fileDimension" key={idx}>
                  <img src={myimg} />
                </div>
              );
            })
          : null}
      </div>
    );
  };

  return (
    <div classname="formOuterWrapper">
      <div classname="formInnerWrapper">
        <div classname="fileUploadContainer">
          <form classname="fileUploadForm " name="myForm" onSubmit={onUpload}>
            <div classname="custom-file mb-5">
              <input
                type="file"
                multiple
                classname="custom-file-input"
                id="customFile"
                onChange={onChangeFile}
              />
              <label classname="custom-file-label" htmlFor="customFile">
                {selectedFile}
              </label>
            </div>

            <div classname="progressbar">
              <ProgressFileUpload percentage={uploadPercentage} />
            </div>

            <input
              type="submit"
              value="Upload"
              classname="btn btn-primary btn-block mt-5"
            />
            <DisplayFile />
          </form>
        </div>
      </div>

    </div>
  );
};

export default UploadDocumentsContainer;

后端文件服务器(fileUploadServer):-

const express = require("express");
const fileUpload = require("express-fileupload");
const morgan = require("morgan");

const app = express();
const path = require("path");
const cors = require("cors");
const port = 9001;
const publicPath = path.join(__dirname,"..","public");
// eslint-disable-next-line no-console
console.log("publicpath",publicPath);
app.use(express.static(publicPath));
app.use(cors());
app.use(fileUpload());
app.use(morgan("dev"));

app.post("/client/public/uploads",(req,res) => {
  if (req.files === null) {
    return res.status(400).json({ msg: "NO FILE UPLOADED" });
  }



  const filename = [],filepath = [];
  if (Object.keys(req.files.file).includes("name")) {
    const file = req.files.file;
    filename.push(file.name);
    filepath.push(`${publicPath}/uploads/${file.name}`);
    file.mv(`${publicPath}/uploads/${file.name}`,err => {
      if (err) {
        console.log("err while moving the file to different directory",err);
        return res.status(500).send(err);
      }
    });
  } else {
    for (let i in req.files.file) {
      const file = req.files.file[i];
      filename.push(file.name);
      filepath.push(`${publicPath}/uploads/${file.name}`);
      console.log("INSIDE UPLOADS",file.name);
      file.mv(`${publicPath}/uploads/${file.name}`,err => {
        if (err) {
          console.log("err while moving the file to different directory",err);
          return res.status(500).send(err);
        }
      });
    }
  }

  console.log(filename,"::::",filepath);

  res.json({ fileName: `${[filename]}`,filePath: `${filepath}` });
});
app.listen(port,() => {
  // eslint-disable-next-line no-console
  console.log(`SERVER IS LISTENING ON PORT ${port}`);
});

目录结构:-

无法在React中使用Webpack和url-loader / file-loader来查看(在后端服务器上)上传的图像

sky43420024420 回答:无法在React中使用Webpack和url-loader / file-loader来查看(在后端服务器上)上传的图像

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2581097.html

大家都在问