Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 带React的弹簧座(dropzone和Formik)_Reactjs_Spring_Spring Rest_Formik_Dropzone - Fatal编程技术网

Reactjs 带React的弹簧座(dropzone和Formik)

Reactjs 带React的弹簧座(dropzone和Formik),reactjs,spring,spring-rest,formik,dropzone,Reactjs,Spring,Spring Rest,Formik,Dropzone,我正在尝试构建一个端点,在这里我可以发布一条带有图像的JSON消息来上传。但每当我从前端发送请求时,都会得到空值 我已经用Postman测试了这个端点,它工作得很好 这是我的服务器代码: @PostMapping public ResponseEntity<Product> createProduct(@ModelAttribute @Valid ProductJson product) { return new ResponseEntity<>(prod

我正在尝试构建一个端点,在这里我可以发布一条带有图像的JSON消息来上传。但每当我从前端发送请求时,都会得到空值

我已经用Postman测试了这个端点,它工作得很好

这是我的服务器代码:

  @PostMapping
  public ResponseEntity<Product> createProduct(@ModelAttribute @Valid ProductJson product) {
    return new ResponseEntity<>(productService.createNewProduct(product), HttpStatus.CREATED);
  }
在前端,我使用react with Formik和dropzone:

export const addProduct = (data) =>
fetch(MANAGEMENT_PRODUCTS_URL, {
    headers: {
      Authorization: 'Bearer ' + localStorage.getItem(ACCESS_TOKEN)
    },
    method: 'POST',
    body: JSON.stringify(data)
  }).then(checkStatus);

<Formik
        className='pt-4'
        initialValues={{
          productName: '',
          productPrice: '',
          categoryId: '',
          productImage: null
        }}
        validationSchema={validationSchema}
        onSubmit={(productForm, { setSubmitting }) => {
          addProduct(productForm)
            .then(res => {
              console.log(res);
              setSubmitting(false);
            })
            .catch(err => {
              console.log(err);
            });
        }}
      >
        {({ submitForm, setFieldValue }) => (
            <Form>
              <FormGroup row>
                  <Field
                    type='productName'
                    name='productName'
                    placeholder='Insert name of the product'
                    as={Input}
                  />
              </FormGroup>
              <FormGroup row>
                  <Field
                    type='text'
                    name='productPrice'
                    placeholder='Insert price of the product'
                    as={Input}
                  />
              </FormGroup>
              <FormGroup row>
                  <Field name='categoryId' component={CategoryDropDown} />
              </FormGroup>
              <FormGroup row>
                  <Dropzone3D setFieldValue={setFieldValue} />
              </FormGroup>
            </Form>
        )}
      </Formik>
export const addProduct=(数据)=>
获取(管理、产品、URL、{
标题:{
授权:'Bearer'+localStorage.getItem(访问令牌)
},
方法:“POST”,
正文:JSON.stringify(数据)
})。然后(检查状态);
{
addProduct(productForm)
。然后(res=>{
控制台日志(res);
设置提交(假);
})
.catch(错误=>{
控制台日志(err);
});
}}
>
{({submitForm,setFieldValue})=>(
)}
这是我上传图片的地方:

export const Dropzone3D = props => {
  const onDrop = useCallback(
    acceptedFiles => {
      let productImage = acceptedFiles[0];
      props.setFieldValue("productImage", productImage);
    },
    [props]
  );

  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  return (
    <div
      {...getRootProps({
        onClick: event => event.preventDefault()
      })}
    >
      <input {...getInputProps()} />
      {isDragActive ? (
        <Button color='info'>Drop the image here ...</Button>
      ) : (
        <Button color='info' outline>
          Drag n drop or click to select an image
        </Button>
      )}
    </div>
  );
};
export const Dropzone3D=props=>{
const onDrop=useCallback(
acceptedFiles=>{
让productImage=acceptedFiles[0];
props.setFieldValue(“productImage”,productImage);
},
[道具]
);
const{getRootProps,getInputProps,isDragActive}=useDropzone({onDrop});
返回(
event.preventDefault()
})}
>
{isDragActive(
把图像放在这里。。。
) : (
拖放或单击以选择图像
)}
);
};

好的,我找到了这个问题的解决方案

  • 我使用axios库而不是fetch
  • 我在Submit方法中创建了一个新的formData对象
  • 我希望我能在这个例子上帮助别人

    <Formik
        className='pt-4'
        initialValues={{
          productName: '',
          productPrice: '',
          categoryId: '',
          productImage: ''
        }}
        validationSchema={validationSchema}
        onSubmit={(product, { setSubmitting }) => {
          const formData = new FormData();
          formData.append('productImage', product.productImage);
          formData.append('productName', product.productName);
          formData.append('productPrice', product.productPrice);
          formData.append('categoryId', product.categoryId);
    
          addProduct(formData)
            .then(res => {
              setSubmitting(false);
            })
            .catch(err => {
              console.log(err);
              setSubmitting(false);
            });
        }}
      >
    
    {
    const formData=new formData();
    formData.append('productImage',product.productImage);
    formData.append('productName',product.productName);
    formData.append('productPrice',product.productPrice);
    formData.append('categoryId',product.categoryId);
    addProduct(formData)
    。然后(res=>{
    设置提交(假);
    })
    .catch(错误=>{
    控制台日志(err);
    设置提交(假);
    });
    }}
    >
    
    <Formik
        className='pt-4'
        initialValues={{
          productName: '',
          productPrice: '',
          categoryId: '',
          productImage: ''
        }}
        validationSchema={validationSchema}
        onSubmit={(product, { setSubmitting }) => {
          const formData = new FormData();
          formData.append('productImage', product.productImage);
          formData.append('productName', product.productName);
          formData.append('productPrice', product.productPrice);
          formData.append('categoryId', product.categoryId);
    
          addProduct(formData)
            .then(res => {
              setSubmitting(false);
            })
            .catch(err => {
              console.log(err);
              setSubmitting(false);
            });
        }}
      >