程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用 nodejs、multer、react 上传文件大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用 nodejs、multer、react 上传文件?

开发过程中遇到使用 nodejs、multer、react 上传文件的问题如何解决?下面主要结合日常开发的经验,给出你关于使用 nodejs、multer、react 上传文件的解决方法建议,希望对你解决使用 nodejs、multer、react 上传文件有所启发或帮助;

我正在尝试从前端上传文件(在反应中)并保存到服务器中的文件系统。当我向服务器发出请求时,请求成功,但文件没有保存到我的文件系统中。当我 console.log req.file 时,我得到一个“未定义”(在服务器端)。

server.Js

const express = require('express')
const app = express()
const port = 5000
const fs = require('fs');
const path = require('path');
const childProcess = require('child_process');
//const { request } = require('express');
const multer = require("multer");

app.use(express.bodyParser({limit: '500000mb'}));


const storage = multer.diskStorage({
    desTination: function(req,file,cb){
        cb(null,"upload/");
    },filename: function(req,cb){
        console.log(req);
        cb(null,"test.png");
    }
})

const upload = multer({storagE});

app.post("/model",upload.single("file"),(req,res) => {
    console.log(req.files);
    res.send("files received");
})


app.use(express.static('build'));

app.Listen(port,() => {
    console.log(`Example app Listening at http://localhost:${port}`)
});

addBtn.Js

import React,{ Component } from "react";
import axios from 'axios';

class AddBtn extends Component{
   
    render(){
        return(
            <div classname="form">
                <form method="post" enctype="multipart/form-data" action="/model">
                    <input type="file" name="file" />
                    <input type="@R_301_5555@" value="upload" />
                </form>
            </div>
        );
    }
}

export default AddBtn;

当我 console.log(req.files) 我得到:

{ file:
   { fIEldname: 'file',originalfilename: 'requerimento.png',path: '/tmp/37648-1b0v335.qt09.png',headers:
      { 'content-disposition': 'form-data; name="file"; filename="requerimento.png"','content-type': 'image/png' },ws:
      WriteStream {
        _writableState: [WritableState],writable: false,_events: [Object],_eventsCount: 2,_maxListeners: undefined,fd: null,flags: 'w',mode: 438,start: undefined,autoClose: true,pos: undefined,bytesWritten: 30082,closed: true },size: 30082,name: 'requerimento.png',type: 'image/png' } }

当我在 filename: 函数中使用 console.log 时,它不会在屏幕上打印任何内容

我遵循了本教程 https://www.youtube.com/watch?v=-3ePnBWFH9o 并且它有效,但是当我尝试在我的代码(使用 react)中实现它时它失败了,我不知道为什么。谁能告诉我我做错了什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

大佬总结

以上是大佬教程为你收集整理的使用 nodejs、multer、react 上传文件全部内容,希望文章能够帮你解决使用 nodejs、multer、react 上传文件所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。