faile to send file with axios to nedb

198 Views Asked by At

hello when i try to send a picture from my client to my nedb server it make him crash i don't know what should i do, please help me
when i tried to send directly the file without append it in data form a get an empty req.file i don't know what should i do to resolve this probleme

Client

import "./share.css";
import {
  PermMedia,
  Label,
  Room,
  EmojiEmotions,
  Cancel,
} from "@material-ui/icons";
import { useContext, useRef, useState } from "react";
import { AuthContext } from "../../context/AuthContext";
import axios from "axios";
import Avatar  from "../../assets/person/noAvatar.png";

export default function Share() {
  const { user } = useContext(AuthContext);
  const PF = process.env.REACT_APP_PUBLIC_FOLDER;
  const desc = useRef();
  const [file, setFile] = useState(null);

  const submitHandler = async (e) => {
    e.preventDefault();
    const newPost = {
      message: desc.current.value
    };
    try {
      //ICI
      const res=await axios.post("apimessages/user/"+user.user._id+"/messages", newPost);
      if (file) {
        const data = new FormData();
        data.append("file", file);
        console.log("new post",newPost);
        
        const test = await axios.post("/apimessages/user/"+user.user._id+"/messages/"+res.data.id+"/uploadpicture", data,{
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
      
      }
    } catch (err) {
      console.log(err);
    }
    
    
  };

  return (
    <div className="share">
      <div className="shareWrapper">
        <div className="shareTop">
          <img
            className="shareProfileImg"
            src={
              user.user.profilePicture
                ? user.user.profile
                : Avatar
            }
            alt=""
          />
          <input
            placeholder={"Tweeter " + user.user.login }
            className="shareInput"
            ref={desc}
          />
        </div>
        <hr className="shareHr" />
        {file && (
          <div className="shareImgContainer">
            <img className="shareImg" src={URL.createObjectURL(file)} alt="" />
            <Cancel className="shareCancelImg" onClick={() => setFile(null)} />
          </div>
        )}
        <form className="shareBottom" onSubmit={submitHandler}>
          <div className="shareOptions">
            <label htmlFor="file" className="shareOption">
              <PermMedia htmlColor="tomato" className="shareIcon" />
              <span className="shareOptionText">Photo</span>
              <input
                style={{ display: "none" }}
                type="file"
                id="file"
                accept=".png,.jpeg,.jpg"
                onChange={(e) => setFile(e.target.files[0])}
              />
            </label>
           
  
            <div className="shareOption">
              <EmojiEmotions htmlColor="goldenrod" className="shareIcon" />
              <span className="shareOptionText">Emoji</span>
            </div>
          </div>
          <button className="shareButton" type="submit">
            Tweeter
          </button>
        </form>
      </div>
    </div>
  );
}

server

router.post(
    "/user/:userid/messages/:messageid/uploadpicture",
    upload.single("file"),
    async (req, res) => { 
      try {
        
        if (req.params.userid != req.session.userid) {
          res.status(401).json({
            status: 401,
            message: "Utilisateur non connecté",
          });
          return;
        }
    
        const user = await users.exists_id(req.params.userid);
        if (!user) {
          res.status(401).json({
            status: 401,
            message: "Userid inconnu",
          });
          return;
        }

        message = await messages.exists_id(req.params.messageid);
        if (!message) {
          res.status(401).json({
            status: 401,
            message: "message id inconnu",
          });
          return; 
        }

        if (
          req.file.detectedMimeType != "image/jpg" &&
          req.file.detectedMimeType != "image/png" &&
          req.file.detectedMimeType != "image/jpeg"
        ) {
          res.status(401).json({
            status: 401,
            message: "Invalid file type",
          });
          return;
        }

        if (req.file.size > 900000000) {
          res.status(401).json({
            status: 401,
            message: "Max size",
          });
          return;
        }

        const fileName = message._id + ".jpg";
        if (!(await messages.upload_picture(req.params.messageid, fileName))) {
          res.status(401).json({
            status: 401,
            message: "Upload picture error",
          });
          return;
        }

        await pipeline(
          req.file.stream,
          fs.createWriteStream(
            `${__dirname}/../../client/public/data/uploads/posts/${fileName}`
          )
        );

        res.status(201).json({ message: "picture uploadé" });
        return;
      } catch (e) {
        // Toute autre erreur
        res.status(500).json({
          status: 500,
          message: "erreur interne",
          details: (e || "Erreur inconnue").toString(),
        });
      }
    }
  );

  return router;
}

the error in server log

node:internal/errors:464 ErrorCaptureStackTrace(err); ^

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received null
    at TempWriteStream.WriteStream (node:internal/fs/streams:325:5)
    at new TempWriteStream (C:\Users\Chihez\projet\projet_birdy\server\node_modules\fs-temp\lib\write-stream.js:6:15)   
    at Object.createWriteStream (C:\Users\Chihez\projet\projet_birdy\server\node_modules\fs-temp\lib\temp.js:121:10)    
    at Busboy.<anonymous> (C:\Users\Chihez\projet\projet_birdy\server\node_modules\multer\lib\read-body.js:70:27)       
    at Busboy.emit (node:events:520:28)
    at Busboy.emit (C:\Users\Chihez\projet\projet_birdy\server\node_modules\busboy\lib\main.js:37:33)
    at PartStream.<anonymous> (C:\Users\Chihez\projet\projet_birdy\server\node_modules\busboy\lib\types\multipart.js:214:13)
    at PartStream.emit (node:events:520:28)
    at HeaderParser.<anonymous> (C:\Users\Chihez\projet\proj    at HeaderParser.emit (node:events:520:er.js:50:16)      28) {                                     28) {
  code: 'ERR_INVALID_ARG_TYPE'
}

client error

Proxy error: Could not proxy request /apimessages/user/WitCt92ufiBORKcw/messages/NuobgPDsq0OLY5M0/uploadpicture from localhost:3000 to http://localhost:4000/.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).

firefox error

Error: Request failed with status code 500
    at createError (createError.js:16:1)
    at settle (settle.js:17:1)
    at XMLHttpRequest.onloadend (xhr.js:54:1)
0

There are 0 best solutions below