首页 > 解决方案 > 反应中动态图像上传422错误

问题描述

我正在尝试通过在响应中提交的动态图像输入上传图像并通过 api 提交并获得 http 错误 422 但在控制台中检查图像数据和所有其他数据正在打印在控制台上附加脚本和错误屏幕截图

我的代码如下: -

import React, { Component,Fragment } from 'react';
import Breadcrumb from '../../../components/common/breadcrumb';

import  { Redirect } from 'react-router-dom';
export class AddProduct extends Component {
constructor(props) {
    super(props)
    this.state = {
        name:"",
        size:"",
        user_manual:"",
        description:"",
        ingredients:"",
        customer_price:"",
        distributor_price:"",
        international_price:"",
        customer_quantity:"",
        distributor_quantity:"",
        sub_category_id:"",
        product_images:[{caption:"",file:""}],
        errormessage:''        }
    this.handleChange = this.handleChange.bind(this)
   }
handleChange = event =>{
this.setState({ [event.target.name]:event.target.value })
}

handleFile=(event)=>{
this.setState({
  file: event.target.files[0]
})
}
handleSubmit = event =>{
event.preventDefault();
let {name,size,
        user_manual,
        description,
        ingredients,
        customer_price,
        distributor_price,
        international_price,
        customer_quantity,
        distributor_quantity,
        sub_category_id, product_images} = this.state;

         
     let data = new FormData();
     data.append('name', name);
     data.append('size', size);
     data.append('user_manual', user_manual);
     data.append('description', description);
     data.append('ingredients', ingredients);
     data.append('customer_price', customer_price);
     data.append('distributor_price', distributor_price);
     data.append('international_price', international_price);
  data.append('customer_quantity', customer_quantity);
 data.append('distributor_quantity', distributor_quantity);
 data.append('sub_category_id', sub_category_id);

 data.append('product_images', product_images)
 console.log(product_images)

 for (var pair of data.entries()) {
console.log(pair[0]+ ', ' + pair[1]); 
 }

 const url ="http://127.0.0.1:8000/api/product"

 console.log("hi");


 new Response(data).text().then(console.log)
 const token = JSON.parse(localStorage.getItem('user'));
    console.log("token",token.data.token);

 const requestOptions={
     method: 'POST', // or ‘PUT’
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers:{ "Content-Type":"application/json",
                    "Accept": 'application/json',
                    'access-control-allow-origin':'*',
                    'Access-Control-Allow-Origin': 'http://localhost:3000',
                    'content-type': 'multipart/form-data',
                Authorization: "Bearer " + token.data.token, } 
  }
  fetch(url, requestOptions)
  // .then(response => response.json())
  .then(function (response) {
  console.log(response.status);
  console.log(response)
 return response.json();
 })

// .then(data => console.log(data.data.errors));
catch(err => console.log(err));
// console.log("error",this.state.errormessage);


}

 handleProduct  (idx, evt)  {
const newProduct_images = this.state.product_images.map((productimage, sidx) => {
  if (idx !== sidx) return productimage;
  return { ...productimage, file: evt.target.value };
});


this.setState({ product_images: newProduct_images });
};
handleProductcaption(idx, evt){
const newProduct_images = this.state.product_images.map((productimage, sidx) => {
  if (idx !== sidx) return productimage;
  return { ...productimage, caption: evt.target.value };
});


 this.setState({ product_images: newProduct_images }); 
 }



 handleAddProduct = () => {
 this.setState({
   product_images: this.state.product_images.concat([{ caption: "", file:""}])
 });
 };

 handleRemoveproduct = idx => () => {
 this.setState({
  product_images: this.state.product_images.filter((s, sidx) => idx !== sidx)
 });
 };





 render() {
    let data1 =(localStorage.getItem("user"));
    if(data1)
    {
            
            data1=JSON.parse(data1);
            console.log(data1.data.token);
    }
    if (data1 === null ) {
           return <Redirect to='/'  />
            } else {
    return (
        <Fragment>
            <Breadcrumb title="Add Products" parent="Product Management" />
            <div className="container-fluid">
                <div className="row product-adding">
                    <div className="col-xl-12">
                        <div className="card">
                            <div className="card-header">
                                <h5>Add Product</h5>
                            </div>
                            <div className="card-body">
                                <div className="digital-add needs-validation">
                                    <form onSubmit={this.handleSubmit} 
      enctype="multipart/form-data">
                                    <div className="form-group">
                                        <label className="col-form-label pt-0"> Product 
        Name</label>
                                        <input className="form-control"  type="text" 
        name="name" onChange={this.handleChange} required="" placeholder="Enter Product Name" 
   />
                                    </div>
                                    <div className="form-group">
                                        <label className="col-form-label pt-0"> Product 
   Size</label>
                                        <input className="form-control"  type="text" 
  required="" name="size" onChange={this.handleChange} placeholder="Enter Product Size"/>
                                    </div>
                                    <div className="form-group">
                                        <label className="col-form-label pt-0"> User 
  Manual</label>
                                        <input className="form-control"  type="text" 
  required="" name="user_manual" onChange={this.handleChange}  placeholder="Enter User 
  Manual"/>
                                    </div>
                                     <div className="form-group">
                                        <label className="col-form-label pt-0"> Enter 
   Description</label>
                                        <input className="form-control"  type="textarea" 
 required="" name="description" onChange={this.handleChange} placeholder="Enter Description"/>
                                    </div>
                                     <div className="form-group">
                                        <label className="col-form-label pt-0"> Enter 
  Ingredients</label>
                                        <input className="form-control"  type="text" 
  required="" name="ingredients" onChange={this.handleChange} placeholder="Enter 
    Ingredients"/>
                                    </div>
                                    <div className="form-group">
                                        <label className="col-form-label pt-0"> Enter Customer 
   Price</label>
                                        <input className="form-control"  type="number"  
  name="customer_price" step="any" onChange={this.handleChange} required=""  
  placeholder="Enter Customer Price"/>
                                    </div>
                                    <div className="form-group">
                                        <label className="col-form-label pt-0"> Enter 
   Distributor Price</label>
                                        <input className="form-control"  type="number"  
  name="distributor_price" step="any" required="" onChange={this.handleChange}  
  placeholder="Enter Distributor Price"/>
                                    </div>
                                    <div className="form-group">
                                        <label className="col-form-label pt-0"> Enter 
 International Price</label>
                                        <input className="form-control"  type="number"  
  name="international_price" step="any" required="" onChange={this.handleChange}  
  placeholder="Enter International Price"/>
                                    </div>
                                    <div className="form-group">
                                        <label className="col-form-label pt-0"> Enter Customer 
  quantity</label>
                                        <input className="form-control"  type="number"  
required="" name="customer_quantity" onChange={this.handleChange} placeholder="Enter 
  Quantity"/>
                                    </div>
                                    <div className="form-group">
                                        <label className="col-form-label pt-0"> Enter 
   Distributor quantity</label>
                                        <input className="form-control"  type="number"  
    required="" name="distributor_quantity" onChange={this.handleChange} placeholder="Enter 
   Quantity"/>
                                    </div>
                                     <div className="form-group">
                                        <label className="col-form-label pt-0"> Enter 
   Subcategory Id</label>
                                        <input className="form-control"  type="number"  
   required="" name="sub_category_id" onChange={this.handleChange} placeholder="Enter 
   Subcategory Id"/>
                                    </div>
                                    <h4>Upload Product</h4>
                                    
                                     {this.state.product_images.map((product_images, idx) => (
                                   <div key={idx} className="form-inline">
                                       <span className="form-group">
                                        <input
                                        type="text"
                                        className="form-control"
                                        placeholder={`productcaption #${idx + 1} caption`}
                                        name="caption"
                                        value={product_images.caption}
                                        onChange={(evt)=>this.handleProductcaption(idx,evt)}
                                        />
                                        </span>
                                    
                                        <span className="form-group">
                                        <input
                                        type="file"
                                        className="form-control"
                                        name="file"
                                        placeholder={`productfile #${idx + 1} file`}
                                        value={product_images.file}
                                        onChange={(evt)=>this.handleProduct(idx,evt)}
                                        />
                                        </span>
                                        <span className="form-group">
                                        <button
                                        type="button"
                                        onClick={this.handleRemoveproduct(idx)}
                                        className="small"
                                        >
                                        -
                                        </button>
                                        </span>
                                    </div>
                                    ))}
                                    <button
                                    type="button"
                                    onClick={this.handleAddProduct}
                                    className="small"
                                    >
                                    Add product
                                    </button>
                                    <div className="form-button">
                                        <button className="btn btn-primary" >Submit</button>
                                    </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                
                </div>
            </div>
         </Fragment>
         )
     }                                             
   }
  }   

export default AddProduct

标签: reactjs

解决方案


推荐阅读