【问题标题】:How to upload image in reactjs using formik如何使用formik在reactjs中上传图片
【发布时间】:2022-11-30 13:33:02
【问题描述】:

如何在 reactjs 中上传图像并使用 formik 表单将其存储到 mysql 数据库中 这是我在 stackoverflow 的另一个问题中找到的代码,但为什么我的代码出现错误,任何人都可以帮助我解决我的问题

import React from 'react';
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import axios from 'axios';


function Registration() {


    const initialValues = {
        firstName: "",
        lastName: "",
        address: "",
        gender: "",
        email: "",
        number: "",
        adminType: "",
        image: "",
        username: "",
        password: "",
    };

    const validationSchema = Yup.object().shape({
        firstName: Yup.string().min(2).required(),
        lastName: Yup.string().min(2).required(),
        address: Yup.string().min(10).required(),
        gender: Yup.string().min(4).max(6).required(),
        email: Yup.string().min(10).required(),
        number: Yup.number().min(11).max(11).required(),
        adminType: Yup.string().required(),
        image: Yup.mixed()
                .required("You need to provide a file")
                .test("fileSize", "The file is too large", (value) => {
                    return value && value[0].sienter <= 2000000;
                })
                .test("type", "Only the following formats are accepted: .jpeg, .jpg, .bmp, .pdf and .doc", (value) => {
                    return value && (
                        value[0].type === "image/jpeg" ||
                        value[0].type === "image/bmp" ||
                        value[0].type === "image/png" ||
                        value[0].type === 'application/pdf' ||
                        value[0].type === "application/msword"
                    );
                }),
        username: Yup.string().min(3).max(20).required(),
        password: Yup.string().min(2).max(20).required(),
    });

    const onSubmit = (data) => {
        axios.post("http://localhost:3001/auth", data).then(() => {
            console.log(data);
        });
    };

    const handleChange = (event) => {
        const reader = new FileReader();
        reader.onload = () => {
            if (reader.readyState === 2) {
                this.setState({file: reader.result})
            }
        } 
        reader.readAsDataURL(event.target.files[0]);
        console.log(this.props.fieldname);
        this.props.sfv("image1", event.currentTarget.files[0]);
    }


    return (
        <div>
            <h1>Registration</h1>
            <Formik
                initialValues={initialValues}
                validationSchema={validationSchema}
                onSubmit={onSubmit}
            >
                <Form>
                    <label>First Name</label>
                    <ErrorMessage name="firstName" component="span"/>
                    <Field
                        autoComplete="off"
                        id="firstName"
                        name="firstName"
                        placeholder= "First Name"
                    />
                    <label>Last Name</label>
                    <ErrorMessage name="lastName" component="span"/>
                    <Field
                        autoComplete="off"
                        id="lastName"
                        name="lastName"
                        placeholder= "Last Name"
                    />
                    <label>Address</label>
                    <ErrorMessage name="address" component="span"/>
                    <Field
                        autoComplete="off"
                        id="address"
                        name="address"
                        placeholder= "address"
                    />
                    <label>gender</label>
                    <ErrorMessage name="gender" component="span"/>
                    <Field
                        autoComplete="off"
                        id="gender"
                        name="gender"
                        placeholder= "gender"
                    />
                    <label>Email</label>
                    <ErrorMessage name="email" component="span"/>
                    <Field
                        autoComplete="off"
                        id="email"
                        name="email"
                        placeholder= "email"
                    />
                    <label>Number</label>
                    <ErrorMessage name="number" component="span"/>
                    <Field
                        type="number"
                        autoComplete="off"
                        id="number"
                        name="number"
                        placeholder= "number"
                    />
                    <label>Admin Type</label>
                    <ErrorMessage name="adminType" component="span"/>
                    <Field
                        autoComplete="off"
                        id="adminType"
                        name="adminType"
                        placeholder= "admin"
                    />
                    <label>Image</label>
                    <ErrorMessage name="image" component="span"/>
                    <input
                        autoComplete="off"
                        id="image"
                        name={this.props.Image}
                        type="file"
                        onChange={this.imageHandler}
                    />
                    <label>Username</label>
                    <ErrorMessage name="username" component="span" />
                    <Field
                        autoComplete="off"
                        id="username"
                        name="username"
                        placeholder="Ex. guko"
                    />
                    <label>Password</label>
                    <ErrorMessage name="password" component="span" />
                    <Field
                        autoComplete="off"
                        type="password"
                        id="password"
                        name="password"
                        placeholder="Ex. guko1234"
                    />
                    <button type="submit">Register</button>
                </Form>
            </Formik>
        </div>
    )
}

export default Registration

我尝试了上面的代码,我的代码出现了错误,这是我的错误看起来像

Compiled with problems:X

ERROR

[eslint] 
src\pages\Registration.jsx
  Line 55:5:  'imageHandler' is not defined  no-undef

Search for the keywords to learn more about each error.

为什么我得到那个错误任何人都可以解决我的问题吗?

【问题讨论】:

  • 您的问题是由于打字错误,与 react、axios 或 formik 无关。在代码顶部的imageHandler 前面添加一个const。我假设没有您应该发布的其他相关代码。
  • 仍然有一个错误说'handleChange'被分配了一个值但从未使用过
  • 我刚刚编辑以显示我的所有代码。
  • 当您不断更改已发布的代码并且需要不同的修复时,很难提供帮助。
  • 我只是更改编辑我的代码以显示我的所有代码

标签: reactjs react-hooks axios formik yup


【解决方案1】:

我解决了关于如何使用 Formik 在 reactjs 前端将图像上传到后端的问题,我只是做了这段代码

{({
   setFieldValue
}) => (
   <Form>
       <label>Image</label>
       <ErrorMessage name="image" component="span"/>
       <input
            autoComplete="off"
            id="image"
            name="image"
            type="file"
            onChange={event => setFieldValue("image",event.currentTarget.files[0])}
       />
   </Form>
)}

我只是在 Formik 标签内声明了 onFieldValue

在我的后端 API 中,我这样做了

  const multer = require("multer");
  const path = require("path");

  const storage = multer.diskStorage({
    destination: "./Image",
    filename: (req, file, cb) => {
        return cb(null, 
 `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
    }
});

const upload = multer({
    storage: storage,
    fileFilter: function(req, file, cb) {
        if(!file.originalname.match(/.(jpg|JPG|jpeg|JPEG|png|PNG)$/)) {
            req.fileValidationError = "Only the image file is allowed";
            return cb(new Error("Only the image file is allowed"), false);
        }
        cb(null, true);
    },
});

router.post("/", upload.single("image"), async (req, res) => {
    const { 
            image = req.file.path,
            username, 
            password,
        } = req.body;
    bcrypt.hash(password, 10).then((hash) => {
        Admin.create({
            image: image,
            username: username,
            password: hash,
        });
        res.json("Success");
    });
});

我使用 multer 库来获取图像

我希望它对任何和我有同样问题的人有帮助:)

【讨论】:

    猜你喜欢
    • 2020-11-13
    • 2019-10-02
    • 2020-08-26
    • 2017-08-03
    • 2021-06-12
    • 2019-12-31
    • 1970-01-01
    • 2022-07-17
    • 1970-01-01
    相关资源
    最近更新 更多