Проблема при загрузке составного файла в react-redux и spring boot

#reactjs #spring-boot #multipartform-data

#reactjs #spring-boot #multipartform-данные

Вопрос:

Я получил исключение, когда пытался добавить составной файл в reactjs, но, когда я использовал postman, я не получил никакой ошибки.

Код загрузки Spring:

 @PostMapping(path = "/products")
    public ResponseEntity<Map<String, Object>> create(@RequestParam("file") MultipartFile file, String jsonRequest,
            HttpServletRequest request) throws FieldNotNullException, JsonProcessingException {
...
}
 

Действие Redux:

 export const createProduct = (file, product, history) => async dispatch => {
    try {
        const response = await axios.post("http://localhost:8282/opsprime/api/products", file, product);
        
        history.push("/admin/products")
        // if errors is null that will not effect to the validation
        dispatch({
            type:GET_ERRORS,
            payload:{}
        })

    } catch (err) {
        dispatch({
            type: GET_ERRORS,
            payload: err.response.data
        })
    }
}
 

Компонент React-ProductCreate:

 onSubmitHandler(e){    
    e.preventDefault();  

    const newProduct = {
    userId: this.state.userId,
    title: this.state.title,
    metaTitle: this.state.metaTitle,
    slug: this.state.slug,
    summary: this.state.summary,
    type: 1,
    sku: this.state.sku,
    discount: this.state.discount,
    price:this.state.price,
    quantity: this.state.quantity,
    shop: 1,
    createdAt: "",
    updatedAt: "",
    publishedAt: "",
    startsAt: "",
    endsAt: "",
    content: "",
    category: [],
    tag: [],
}

console.log(this.state.file);
const myJSON = JSON.stringify(newProduct)

    this.props.createProduct(this.state.file, newProduct, this.props.history);


}
 

Результат ошибки:

 ...org.springframework.web.multipart.MultipartException: Current request is not a multipart request
 

Когда я использовал postman, где я мог получить успешный результат,

введите описание изображения здесь

Я получил файл с помощью,

 <FormGroup>
    <Label for="exampleProductImage">Product Image</Label>
     <Upload name="file" istType="picture-card" className="avatar-uploader"
             showUploadList={false}  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              beforeUpload={beforeUpload}
              onChange={this.handleImageChange}
                                                    >
      {imageUrl ? <img src={imageUrl} alt="file" style={{ width: '100%' }} /> : uploadButton}
    </Upload>
</FormGroup>
 

и,

 handleImageChange = info => {
    if (info.file.status === 'uploading') {
        this.setState({ loading: true });
        return;
    }
    if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl =>
        this.setState({
            imageUrl,
            loading: false,
            file:info.file
        }),
        );
    }
    };
 

итак, не могли бы вы уточнить, как отправить данные формы из react в spring boot?

Комментарии:

1. Я предполагаю, что вы пытаетесь из браузера. Как вы загружаете файл?

2. теперь я загрузил дополнительный код, который поможет понять, как я получил файл..