首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >定义了Req.files和req.files

定义了Req.files和req.files
EN

Stack Overflow用户
提问于 2021-01-26 07:31:09
回答 1查看 443关注 0票数 0

当我试图上传使用multer的单个和一系列图像时,我被困住了。这个过程是与邮递员一起工作的,但当我通过React发布时,会传递未定义的req.file。下面是代码片段

前端product.js

代码语言:javascript
复制
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" />

前端productAction.js

代码语言:javascript
复制
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')
            )
            })

后端product.js *

代码语言:javascript
复制
//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)

谁来帮忙请你帮上几天忙

EN

回答 1

Stack Overflow用户

发布于 2021-01-27 07:08:40

我遵循@Quentin指南,在使用FormData和e.target.files之后,我成功地发送了一个文件。当我要附加多个for (let i = 0; i < photos.length; i++) { data.append('photos', photos[i]) } photos.In handlePhotos函数e.target.files时,必须添加e.target.files。

谢谢

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65897351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档