Почему мои formData в req.files? multer node.js - PullRequest
0 голосов
/ 16 марта 2020

Я пытаюсь загрузить pi c в moongoDB, я не знаю почему, но мой отправленный файл заканчивается в req.files вместо req.file, и промежуточное ПО не может его увидеть, что я делаю неправильно? des c внизу console.log ()

Как заставить мое промежуточное ПО читать файл из того места, где он хранится?

реагирует на компоненты

import React, { useState } from 'react'
import { connect } from 'react-redux'
import { uploadPhoto } from '../../actions.js/image'

const Image = ({uploadPhoto}) => {
    const[file, setFile] = useState(null)

    const onChange = e => {
        setFile(e.target.files[0])
    }

    const onSubmit = e => {
        e.preventDefault()
        const formData = new FormData()
        formData.append('file', file)
        uploadPhoto(formData)
    }

    return (
        <div>
            <form onSubmit={onSubmit} encType='multipart/form-data' >
            <input type='file' name='file' onChange={onChange} accept="image/*" /> <br/>
            <button>Submit Photo</button> <br/> <br/>
            </form>
        </div>
    )
}

export default connect(null, {uploadPhoto})(Image)

action

import axios from 'axios'

//upload photo
export const uploadPhoto = formData => async dispatch => {
    try {
        const res = await axios.post('/image', formData)
        console.log(res)
    } catch (err) {

    }
}

route

const express = require('express')
const crypto = require("crypto")
const path = require("path")
const router = express.Router()
const mongoose = require('mongoose')
const config = require('config')
const db = config.get('mongoURI')
const multer = require('multer')
const GridFsStorage = require('multer-gridfs-storage')
const Grid = require('gridfs-stream')

// connection
const conn = mongoose.connection

// Initialize gfs
let gfs

// Initialize gfs stream
conn.once('open', () => {
  gfs = Grid(conn.db, mongoose.mongo);
  gfs.collection('uploads');
})

// Create Storage Engine
const storage = new GridFsStorage({
  url: db,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      // Create a unique 16 character filname
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename = buf.toString('hex') + path.extname(file.originalname)
        const fileInfo = {
          filename: filename,
          bucketName: 'uploads' //should match gfs.collection
        };
        resolve(fileInfo);
      });
    });
  }
});
const upload = multer({ storage })

router.post('/', upload.single('file'), (req, res) => {
  console.log(req)
  //res.json(req)
})


module.exports = router


console.log (req) от маршрута в узле

[0]   body: [Object: null prototype] {},
[0]   originalMethod: 'POST',       
[0]   files: {
[0]     file: {
[0]       name: 'code-1839406_1920.jpg',
[0]       data: <Buffer ff d8 ff e0 
00 10 4a 46 49 46 00 01 01 01 01 2c 
01 2c 00 00 ff db 00 43 00 05 03 04 
04 04 03 05 04 04 04 05 05 05 06 07 
0c 08 07 07 07 07 0f 0b 0b 09 ... 556803 more bytes>,
[0]       size: 556853,
[0]       encoding: '7bit',
[0]       tempFilePath: '',
[0]       truncated: false,
[0]       mimetype: 'image/jpeg',   
[0]       md5: '833bbfcb2c1a840edfa2b04b19c7ce14',
[0]       mv: [Function: mv]        
[0]     }
[0]   },
[0]   route: Route {
[0]     path: '/',
[0]     stack: [ [Layer], [Layer] ],[0]     methods: { post: true }     
[0]   }
[0] }
...