как импортировать файлы из папки загрузки и по пути, сохраненному в схеме mongoose - PullRequest
0 голосов
/ 17 мая 2019

Я новичок, чтобы реагировать.Я пытаюсь загрузить и отобразить изображение в реакции.Я использую mongodb для хранения пути к изображению с помощью multer в nodejs, поэтому я успешно справился с загрузкой изображения, я использую робота 3t.Я вижу, что путь к изображению загружен.

Но теперь, когда я пытаюсь получить доступ к пути к изображению из реакции, я получаю эту ошибку в консоли Chrome:

GET http://localhost:3000/api/FichesPatients/uploads/57852721_310708826272290_1281173974004269056_n.png 401 (неавторизовано)

Любая помощь, пожалуйста?

Код для загрузки внутри папки загрузки из внутреннего узлаjj, используя multer:

const multer = require("multer");
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, "./uploads/");
  },
  filename: function(req, file, cb) {
    cb(null, file.originalname);
  }
});
const fileFilter = (req, file, cb) => {
  // reject a file
  if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};
const upload = multer({
  storage: storage
});

app.use("/uploads", express.static("uploads")); 

Код для публикации нового fichepatient с profileimage:

app.post(
  "/api/FichesPatients/Nouveau",
upload.single("file"),
 async function(req, res, next) {
    try {
      console.log(req.file);
      let fichePatient = await db.FichePatient.create({
        email: req.body.email,
        nom: req.body.nom,
        prenom: req.body.prenom,
        cin: req.body.cin,
        profileImageUrl: req.file.path,
        gender: req.body.gender,
        adresse: req.body.adresse,

        tel: req.body.tel,
        dateNaissance: req.body.dateNaissance,
        creator: req.userId
      });


      return res.status(200).json(fichePatient);
    } catch (err) {
      return next(err);
    }
  }
);

И это код для загрузки файла:

this.state = {
profileImageUrl: ""}

  onChangeHandler(event) {
    console.log(event.target.files[0]);
    this.setState({
      profileImageUrl: event.target.files[0],
      loaded: 0
    });
  }
  onClickHandler = () => {
    const data = new FormData();
    data.append("file", this.state.profileImageUrl);
    axios
      .post("/api/FichesPatients/Nouveau", data, {
        // receive two  parameter endpoint url ,form data
      })
      .then(res => {
        // then print response status
        console.log(res.statusText);
      });
  };

  <input
            type="file"
            name="profileImageUrl"
            onChange={this.onChangeHandler}
          />
          <button
            type="button"
            class="btn btn-success btn-block"
            onClick={this.onClickHandler}
          >
            Upload
          </button>

Для отображения информации о пациенте я использую эту функцию

exports.afficherFichePatient = async function(req, res, next) {
  try {
    // let message = await db.Message.findById(req.params.message_id);
    let fichePatient = await db.FichePatient.findById(
      req.params.fichePatient_id
    ).populate("creator", {
      nomD: true
    });
    return res.status(200).json(fichePatient);
  } catch (err) {
    return next(err);
  }
};

С этим маршрутом:

app.post(
  "/api/FichesPatients/");

и для части отображения реакции это так:

componentDidMount() {
    axios
      .get("/api/FichesPatients/" + this.props.match.params.id)
      .then(response => {
        this.setState({
          nom: response.data.nom,
          prenom: response.data.prenom,
          gender: response.data.gender,
          profileImageUrl: response.data.profileImageUrl,
          cin: response.data.cin,
          adresse: response.data.adresse,
          tel: response.data.tel,
          email: response.data.email
        });
      })
      .catch(function(error) {
        console.log(error);
      })}

<MDBCardImage
                className="mx-auto hoverable d-block  rounded-circle"
                src={this.state.profileImageUrl}
                width="100px"
                height="130px"
              />

и для моей схемы мангуста это так:

const fichePatientSchema = new mongoose.Schema(
  {
    //info from the app
    email: {
      type: String
      //unique: true
    },
    profileImageUrl: {
      type: String
    },
...