G
G
gallantalex2017-05-27 13:48:36
JavaScript
gallantalex, 2017-05-27 13:48:36

How to implement image sending in react+redux application?

I have a React + Redux project. And on one form, you need to implement adding a picture. This data from the form will be sent to the server. If everything is clear with simple data types: I extract lines from the form fields, pass them to the action creator, and from there this data is sent to the server, and also stored in the global state. But I cannot transfer the file to the action creator. How to proceed in such a case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel, 2018-09-01
@mrusklon

js is not needed, it is done in css

M
Maxim, 2017-05-27
@gallantalex

Why can't you? This is also a normal form field.
I looked at the old project where I did it. It was like this:

...
const request = require('superagent-bluebird-promise')
...
export function addProduct(formData) {
  return dispatch => {
    dispatch({ type: PRODUCT_ADD_REQUEST })
    if (formData.image) {
      return request.post(`${API_ROOT_V1}/api/v1/products/add`)
        .field('name', formData.name)
        .field('price', formData.price)
        .field('description', formData.description)
        .field('providerId', formData.providerId)
        .attach('image', formData.image, formData.image.name) // добавление картинки
        .then(...) // здесь дальнейшая обработка в случае успеха
    } else { // кейс, когда у товара нет картинки
      return request.post(`${API_ROOT_V1}/api/v1/products/add`)
        .send(formData)
        .then(...)
    }
  }
}

In the code of the formData component, I form it like this:
... 
// (обработчик сабмита формы)
this.props.addProduct({
      name,
      price,
      description,
      image: findDOMNode(this.refs.image).files[0], // (забираю картинку)
      providerId: this.props.providerId,
    })
...

// непосредственно кнопка загрузки файла в форме
<div className='form-group'>
          <input
            id='productImage'
            type='file'
            name='image'
            placeholder='Image'
            onChange={this.handleChange}
            value={this.state.image}
            data-field-name='image'
            ref='image' />
          <p>Load product image</p>
        </div>
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question