如何将图像从客户端发送到服务器节点 js 反应 [英] How can I send image from client to server node js react

查看:48
本文介绍了如何将图像从客户端发送到服务器节点 js 反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建上传个人资料图片方法,帮助用户在网站上上传他们的个人资料图片,但我不知道如何将图像从客户端发送到服务器并将这些图像存储在 cloudinary 或 firebase 上.

我的路线如下所示:ProfileAPI.js

 const express = require(express");const router = express.Router();const { body, param } = require(express-validator");const { catchErrors } = require("../errors/errorHandlers");const multer = require('multer');const uuidv4 = require('uuid/v4');const upload_dir = './images';const 存储 = multer.diskStorage({目的地:(请求,文件,cb)=>{cb(null,upload_dir);},文件名: (req, file, cb) =>{cb(null, `${uuidv4()}-${file.filename.toLowerCase}`);}});const 上传 = multer({存储:存储,fileFilter: (req, file, cb) =>{如果 (file.mimetype == '图像/png' ||file.mimetype == '图像/jpg' ||file.mimetype == '图像/jpeg'){cb(空,真);} 别的 {cb(空,假);return cb(new Error('只允许 .png、.jpg 和 .jpeg 格式!'));}}});常量{获取用户配置文件,getUsersPublicProfile,查找 ID,更新用户资料,更新用户邮箱,删除用户配置文件,//删除用户技能,添加玩家资料,获取创建的玩家,更新玩家资料,删除用户创建的播放器,} = require("./profilesController");路由器.post(/上传",上传.single('profileImg'),更新用户资料);

所以关键点是设置存储告诉哪里上传+上传文件过滤器,对吗?

还有将 `upload.single('profileImg') 的 route.post,对吗?该路由将包括我的 updateUserProfile 控制器,可在此处找到:profilesController.js

exports.updateUserProfile = async (req, res) =>{const userId = req.session.passport.user.id;//该数组将包含所有要运行的更新函数.常量更新 = [];//如果尚未生成gravatar url,请立即生成.const 图片值 = gravatar.url(req.body.email,{ s:100",r:pg",d:复古"},真的);常量有效载荷 = {全名:req.body.fullname,位置:req.body.location,网页:req.body.webpage,链接:req.body.linkedin,机构:req.body.institution,生物:req.body.bio,主要:req.body.major,合并到:用户 ID,图片:图片值,技能:req.body.skillone,技能二:req.body.skilltwo,技能三:req.body.skillthree};}

现在是前端代码(react.js):

这是我在 React 应用程序中加载的表单:

UserProfile.js

const UserProfile = (serverUserData) =>{const appState = useContext(GlobalContext);const { currentUser } = appState;const { 电子邮件、图片、姓名 } = currentUser;const [isVerified, setIsVerified] = useState(false);const checkVerificationData = () =>{axios.get("/api/v1/profiles/profile").then((res) => {const { 数据 } = res;如果(data.verifiedDT){setIsVerified(data.verifiedDT);}});};useEffect(() => {检查验证数据();}, [isVerified]);//上传用户头像函数const [imageSelected, setImageSelected] = useState("");const handleSubmit = (e) =>{e.preventDefault();const formData = new FormData();formData.append('email', email);formData.append('name', name);formData.append('profileImg', imageSelected);公理.post(`/upload`, formData).then(() => console.log(成功")).catch(err => console.log(err));};const onFileChange = (e) =>{setImageSelected({ profileImg: e.target.files[0] });};};const 类 = useStyles();返回 (<div className={classes.root}><网格项 xs={12}容器方向=行"justify =中心"alignItems=中心"间距={4}><网格项目><网格项目><用户卡图片={当前用户.图片}用户电子邮件={电子邮件}名称={名称}isVerified={isVerified}句柄提交={句柄提交}onFileChange={onFileChange}/><br/></网格>

这里是用户可以上传他们的个人资料照片的地方:UserCard.js

 {图片?(<div><阿凡达src={图片}alt=阿凡达"className="avatar--profile_image";/><输入类型=文件"onChange={onFileChange}/><button onClick={handleSubmit}>提交</button>

) : (<AccountCircleIcon className="avatar--profile_image";/>)}

因此,当输入内容并点击添加按钮时,我的 api 声明 req.file 未定义,我无法找出原因.

谁能帮我分析错误?

解决方案

要上传文件,您需要使用 contentType: multipart/form-data".参考以下实现文件上传.

helper 函数来创建一个带有所需标头的实例.您可以在此处添加任何其他人.

const getInstance = () =>{返回 axios.create({标题:{内容类型":多部分/表单数据",},});}

使用要上传的文件调用此方法

const fileUplaod = (file) =>{让 formData = new FormData();formData.append("images", file, file.name);获取实例().post(endpoint_post_url, formData).then((响应) => {console.log("IMAGES_SUBMIT_SUCCESS");}).catch((错误) => {console.error("图片提交错误", err);});}

检查后端代码中的请求正文.您也可以将多张图片上传到同一媒体资源.它将是请求对象中的一个数组.

I am trying to create upload profile image method that help user upload their profile picture on website but I am having trouble with I dont know how to send the image from client to server and make those image store on cloudinary or firebase.

My routes look like this: ProfileAPI.js

    const express = require("express");
    const router = express.Router();
    const { body, param } = require("express-validator");
    const { catchErrors } = require("../errors/errorHandlers");
    const multer = require('multer');
    const uuidv4 = require('uuid/v4');
    
    const upload_dir = './images';
    
    const storage = multer.diskStorage({
      destination: (req, file, cb) => {
        cb(null, upload_dir);
      },
      filename: (req, file, cb) => {
        cb(null, `${uuidv4()}-${file.filename.toLowerCase}`);
      }
    });
    
    const upload = multer({
      storage: storage,
      fileFilter: (req, file, cb) => {
        if (
          file.mimetype == 'image/png' ||
          file.mimetype == 'image/jpg' ||
          file.mimetype == 'image/jpeg'
        ) {
          cb(null, true);
        } else {
          cb(null, false);
          return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
        }
      }
    });
const {
  getUserProfile,
  getUsersPublicProfile,
  lookUpId,
  updateUserProfile,
  updateUserEmail,
  deleteUserProfile,
  // deleteUserSkill,
  addPlayersProfile,
  getCreatedPlayers,
  updatePlayersProfile,
  deleteUserCreatedPlayer,
} = require("./profilesController");
    
    router.post(
      "/upload",
      upload.single('profileImg'),
      updateUserProfile
    );

So key points are the setup of storage which tells where to upload + the file filter in upload, right?

And the route.post which will `upload.single('profileImg'), right? the route will include my controller for updateUserProfile which can be found here: profilesController.js

exports.updateUserProfile = async (req, res) => {
  const userId = req.session.passport.user.id;
  // This array will contain all the update functions to run.
  const updates = [];

  // If a gravatar url has not been generated, do it now.
  const pictureValue = gravatar.url(
    req.body.email,
    { s: "100", r: "pg", d: "retro" },
    true
  );

  const payload = {
    fullname: req.body.fullname,
    location: req.body.location,
    webpage: req.body.webpage,
    linkedin: req.body.linkedin,
    institution: req.body.institution,
    bio: req.body.bio,
    major: req.body.major,
    mergedTo: userId,
    picture: pictureValue,
    skillone: req.body.skillone,
    skilltwo: req.body.skilltwo,
    skillthree: req.body.skillthree
  };
}

So now to the frontend code (react.js):

This is the form I am loading in my react app:

UserProfile.js

const UserProfile = (serverUserData) => {
  const appState = useContext(GlobalContext);
  const { currentUser } = appState;
  const { email, picture, name } = currentUser;
  const [isVerified, setIsVerified] = useState(false);

  const checkVerificationData = () => {
    axios.get("/api/v1/profiles/profile").then((res) => {
      const { data } = res;   
      if (data.verifiedDT) {
        setIsVerified(data.verifiedDT);
      }
    });
  };

  useEffect(() => {
    checkVerificationData();
  }, [isVerified]);


    // Upload user avatar function
  const [imageSelected, setImageSelected] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('email', email);
    formData.append('name', name);
    formData.append('profileImg', imageSelected);

    axios
      .post(`/upload`, formData)
      .then(() => console.log("success"))
      .catch(err => console.log(err));
  };

  const onFileChange = (e) => {
    setImageSelected({ profileImg: e.target.files[0] });
  };
    };

 const classes = useStyles();
  return (
    <div className={classes.root}>
      <Grid item xs={12}
        container
        direction="row"
        justify="center"
        alignItems="center"
        spacing={4}>
        <Grid item>
          <Grid item>
            <UserCard
              picture={currentUser.picture}
              userEmail={email}
              name={name}
              isVerified={isVerified}
              handleSubmit={handleSubmit}
              onFileChange={onFileChange}
            />
            <br />
          </Grid>
        

and here is where user can upload their profile photo: UserCard.js

  {picture ? (
    <div>
      <Avatar
        src={picture}
        alt="Avatar"
        className="avatar--profile_image"
      />  
      <input
        type="file"
        onChange={onFileChange}
      />  
      <button onClick={handleSubmit}>Submit</button>
    </div>
  ) : (
    <AccountCircleIcon className="avatar--profile_image" />
  )}

So when entering things and hitting the Add Button my api states that req.file is undefined and I cannot find out why.

Can anyone help me drilling down the error?

解决方案

To upload files you need to use contentType: "multipart/form-data". Use the following as a reference to achieve the file upload.

helper function to create a instance with requied header. You may add any others to here.

const getInstance = () => {
  return axios.create({
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}

call this method with the file to be uploaded

const fileUplaod = (file) => {

    let formData = new FormData();
    formData.append("images", file, file.name);
    
    getInstance()
      .post(endpoint_post_url, formData)
      .then((response) => {
        console.log("IMAGES_SUBMIT_SUCCESS");
      })
      .catch((err) => {
        console.error("image submit error", err);
      });
}

check the request body in your backend code. You can upload multiple images as well to the same property. It will be an array in the request object.

这篇关于如何将图像从客户端发送到服务器节点 js 反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆