在反应中添加多个字段,例如单个图像和多个图像

时间:2020-10-06 16:14:46

标签: node.js reactjs mongodb react-redux multer

我想使用multer,react-redux添加单个和多个图像。我想将单个图像添加为缩略图,将多个图像添加为图库,我使用 new FormData()附加所有图像,并且在后端使用 upload.fields([{ :multer选项的'image',maxCount:1},{name:'gallery',maxCount:10}]

import Axios from 'axios';
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addHotel } from '../actions/hotelAction';

function Admin() {
   const [title, setTitle] = useState('');
   const [description, setDescription] = useState('');
   const [capacity, setCapacity] = useState('');
   const [price, setPrice] = useState('');
   const [size, setSize] = useState('');
   const [image, setImage] = useState('');
   const [gallery, setGallery] = useState([]);
   const dispatch = useDispatch();
   const handleSubmit = e => {
      e.preventDefault();
      dispatch(
         addHotel({
            title,
            description,
            capacity,
            size,
            price,
            image,
            gallery,
         }),
      );
   };
   const uploadImageHandler = e => {
      const file = e.target.files[0];
      const bodyFormData = new FormData();
      bodyFormData.append('image', file);
      Axios.post('/api/hotels/uploads', bodyFormData, {
         headers: {
            'Content-Type': 'multipart/form-data',
         },
      })
         .then(res => setImage(res.data))
         .catch(err => console.log(err));
   };
   const uploadGalleryHandler = e => {
      const [...files] = e.target.files;
      let [...galleryImage] = files.map(file => {
         return file.name;
      });
      console.log('GALLERY-IMAGE=>', galleryImage);
      const bodyFormData = new FormData();
      for (let i = 0; i < galleryImage.length; i += 1) {
         bodyFormData.append(galleryImage[i], galleryImage[i]);
      }
      Axios.post('/api/hotels/uploads', bodyFormData, {
         headers: {
            'Content-Type': 'multipart/form-data',
         },
      })
         .then(res => {
            console.log('res=> ', res);
            setGallery(res.data);
            console.log('Gallery =>', gallery);
         })
         .catch(err => console.log(err));
   };
   return (
      <div className='container'>
         <h1 style={{ textAlign: 'center', padding: '10px' }}>
            Resort Admin Page
         </h1>
         <div className='row'>
            <div className='col-sm'>
               <form
                  onSubmit={handleSubmit}
                  style={{
                     border: 'solid 2px #f0932b',
                     padding: '25px',
                     borderRadius: '20px',
                  }}
               >
                  <div class='row mb-4'>
                     <div class='col'>
                        <div class='form-outline'>
                           <input
                              type='text'
                              value={title}
                              placeholder='Title'
                              onChange={e => {
                                 setTitle(e.target.value);
                              }}
                              name='title'
                              placeholder='title'
                              id='form6Example1'
                              class='form-control'
                           />
                        </div>
                     </div>
                     <div class='col'>
                        <div class='form-outline'>
                           <input
                              type='text'
                              value={image}
                              placeholder='Image'
                              onChange={e => {
                                 setImage(e.target.value);
                              }}
                              name='image'
                              id='form6Example2'
                              class='form-control'
                           />
                        </div>
                     </div>
                  </div>
                  <div class='form-outline mb-4'>
                     <input
                        type='file'
                        onChange={uploadImageHandler}
                        id='form6Example3'
                        class='form-control'
                     />
                  </div>
                  <div class='form-outline'>
                     <input
                        type='text'
                        value={gallery}
                        placeholder='Gallery'
                        onChange={e => {
                           setGallery(e.target.value);
                        }}
                        name='gallery'
                        id='form6Example2'
                        class='form-control'
                     />
                  </div>
                  <div class='form-outline mb-4'>
                     <input
                        type='file'
                        onChange={uploadGalleryHandler}
                        id='form6Example3'
                        class='form-control'
                        multiple
                     />
                  </div>
                  <div class='form-outline mb-4'>
                     <input
                        type='number'
                        value={capacity}
                        placeholder='Capacity'
                        onChange={e => {
                           setCapacity(e.target.value);
                        }}
                        name='capacity'
                        id='form6Example3'
                        class='form-control'
                     />
                  </div>
                  <div class='form-outline mb-4'>
                     <input
                        type='number'
                        value={price}
                        placeholder='Price'
                        onChange={e => {
                           setPrice(e.target.value);
                        }}
                        name='price'
                        id='form6Example4'
                        class='form-control'
                     />
                  </div>
                  <div class='form-outline mb-4'>
                     <input
                        type='number'
                        value={size}
                        placeholder='Size'
                        onChange={e => {
                           setSize(e.target.value);
                        }}
                        name='size'
                        id='form6Example5'
                        class='form-control'
                     />
                  </div>
                  <div class='form-outline mb-4'>
                     <textarea
                        type='text'
                        class='form-control'
                        placeholder='Description'
                        value={description}
                        onChange={e => {
                           setDescription(e.target.value);
                        }}
                        name='description'
                        id='form6Example7'
                        rows='4'
                     ></textarea>
                  </div>
                  <button
                     type='submit'
                     class='btn btn-warning btn-lg btn-block mb-4'
                     style={{ color: '#000', fontWeight: 'bold' }}
                  >
                     Create New Hotel Info
                  </button>
               </form>
            </div>
         </div>
      </div>
   );
}

export default Admin;

Action.js

import axios from "axios";
const {
  HOTEL_LIST_REQUEST,
  HOTEL_LIST_SUCCESS,
  HOTEL_LIST_FAIL,
} = require("../constants/hotelConstants");

const listHotel = () => async (dispatch) => {
  try {
    dispatch({
      type: HOTEL_LIST_REQUEST
    });
    const {
      data
    } = await axios.get("api/hotels");
    dispatch({
      type: HOTEL_LIST_SUCCESS,
      payload: data
    });
  } catch (error) {
    dispatch({
      type: HOTEL_LIST_FAIL,
      payload: error
    });
  }
};
const addHotel = (hotel) => async (dispatch) => {
  try {
    dispatch({
      type: HOTEL_LIST_REQUEST,
      payload: hotel
    });
    const {
      data
    } = await axios.post("api/hotels", hotel);
    dispatch({
      type: HOTEL_LIST_SUCCESS,
      payload: data
    });
  } catch (error) {
    dispatch({
      type: HOTEL_LIST_FAIL,
      payload: error
    });
  }
};
export {
  listHotel,
  addHotel
};

使用multer和nodejs的后端代码


router.post('/uploads', upload.fields([{name:'image',maxCount:1},{name:'gallery',maxCount:10}]), (req, res) => {
    // console.log("=>=>=>",req.files);
    // res.send(req.files);
    var imageFile = typeof req.files['image'] !== 'undefined' ? res.write(req.files.image[0].filename) :'';
    const files = req.files['gallery'];
    console.log(files);
        if (typeof files === 'undefined') {
            console.log('ider aa raha hu');
            var gallery = [];
        } else {
            gallery = files.map(file => res.write(file));
        }
    res.send(gallery);
});

0 个答案:

没有答案