axios 如何使用formik在reactjs中上传图片

uemypmqf  于 2022-12-04  发布在  iOS
关注(0)|答案(1)|浏览(158)

我如何上传图片在reactjs和存储到mysql数据库我使用formik形式这是代码我发现在另一个问题在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.

为什么我得到了这个错误有人能解决我问题吗?

fd3cxomn

fd3cxomn1#

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

{({
   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库来获取图像
我希望这对任何和我有同样问题的人都有帮助:)

相关问题