Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

javascript - Req.files and req.files are defined

I am stuck when i try to upload both single and an array of images using multer. The process is working with postman but delivering undefined req.file(s) when i post through React. Below is code snippets

frontend product.js

class Products extends Component {
    state = {
        name: '',
        quantity: '',
        price: '',
        description: '',
        offer: '',
        manufacturer: '',
        expiryDate: null,
        photos: [],
        msg:'',
        show:false,
        approved:'',
        reviews: '',
        category: ''
    }
    static propTypes = {
        loadProducts: PropTypes.func.isRequired,
        saveProduct: PropTypes.func.isRequired,
        error500: PropTypes.bool,
        error: PropTypes.object.isRequired,
        clearErrors: PropTypes.func.isRequired,
        clearSuccess: PropTypes.func.isRequired,
        returnSuccess: PropTypes.func.isRequired
    }
    componentDidMount() {
        
        
        this.props.loadProducts()
        this.props.clearErrors()
        
        
        
    }
    componentDidUpdate(prevProps) {
        const { error} = this.props
        
        if (error !== prevProps.error) {
            //check for PRODUCT error
            if (error.id === 'PRODUCT-ERROR') {
                this.setState({ msg: error.msg.message })
            } else {
                this.setState({ msg: null })

            }
        }
        
        
    }
    handleChange = (e) => {
        this.setState({ [e.target.name]: e.target.value })
    }
    handleEditorChange = (description, editor) => {
        this.setState({'description': description});
      }
    handlePhotos =(e)=>{
       
        this.setState({photos:e.target.files})
        
    }
    handleSubmit =(e) =>{
        e.preventDefault();
        const { name,quantity,price,description, offer,manufacturer,
        expiryDate,photos,approved,reviews,category
        }= this.state
        
        const product ={name,quantity,price,description, offer,manufacturer,
            expiryDate,photos,approved,reviews,category};
        
        
        this.props.saveProduct(product);
        this.props.clearErrors()
    }
 <Form onSubmit={this.handleSubmit} enctype="multipart/form-data">
<Form.File
                                                        onChange={this.handlePhotos}
                                                        accept="image/*"
                                                        multiple
                                                        name='photos'
                                                        type='file'
                                                        placeholder="Product photos" />

frontend productAction.js

export const saveProduct =({ name,quantity,price,description, offer,manufacturer,
    expiryDate,photos,approved,reviews,category
    }) =>async (dispatch) =>{
        console.log(photos)
    //Headers
    const headers = {
        
            'Content-Type':'multipart/form-data'
            
        
    }
    //Request Body
    
    
    const data = { name,quantity,price,description, offer,manufacturer,
        expiryDate,photos,approved,reviews,category
        }
    
    console.log(data)
    await axios.post('http://127.0.0.1:2000/api/product/create',data,headers)
        
        .then(res =>{
            dispatch({
            type: CREATE_PRODUCT,
            payload: res.data,
            
            })
            dispatch(
                returnSuccess(res.data,res.status,'PRODUCT-CREAT-SUCCESS')
            )
            })

***backend product.js ***

//initialize app
const app= express();

//initialize cors
app.use(cors());

//initialize bodyparser
app.use(express.urlencoded({extended:true}));
app.use(express.json());
const storage = multer.diskStorage({
    
    filename:  function (req, file, cb) {
        cb(null, shortid.generate()+ '-' + file.originalname)
    },
})
const uploads = multer({storage:storage,fileFilter: (req, file, cb) => {
    if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") {
        cb(null, true);
    } else {
        cb(null, false);
        return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
    }
}});
router.post('/product/create',uploads.array('photos',10),
        async(req,res,next)=>{
            //res.status('200').json({file:req.files, body: req.body})
            let photos =[]
            console.log(req.files)

Someone help please am stuck for days

question from:https://stackoverflow.com/questions/65897351/req-files-and-req-files-are-defined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

i followed @Quentin guide and after using FormData and using e.target.files[0] i managed to send a single file. I had to add for (let i = 0; i < photos.length; i++) { data.append('photos', photos[i]) } when i was to append multiple photos.In handlePhotos function e.target.files

Thank you


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...