在 React 中上传文件并将其发送到 Express 服务器

IT技术 node.js reactjs
2021-05-19 00:47:24

我需要在 React 中上传一个文件,然后将其发送到 Express 服务器(我是 Express 的新手,所以对我来说很难),

我成功地在我的 React 组件中上传了文件,但现在我不知道如何将它发送到我用 Express 制作的后端服务器。

我需要使用什么?Axios 还是 Fetch?获取还是发布?谢谢 !

我的 App.js 文件(前端)

    uploadFile = () => {
    const { currentFileName, currentFileType } = this.state;
    if (currentFileName && currentFileType) {
      fetch('http://localhost:5000/upload/files', {
        method: "POST",
        headers: {
          'Content-type': 'application/json'
        },
        body: JSON.stringify(this.state)
      })
      .then((res) => res.json())
      .then(res => {
        this.setState({
          errorMessage: "",
          successMessage: `Votre fichier ${currentFileName} a bien été uploadé !`
        });
        console.log(res);
        console.log(res.data);
      })
    } else {
      this.setState({
        errorMessage: "Veuillez choisir un fichier avant d'appuyer sur le bouton Upload !"
      });
    }
  }

和我的 server.js 文件(后端)

const express = require('express');

const app = express();

const router = express.Router();

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
next();
});

const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.post('/upload/files', (req, res) => {
    var fileName = req.body.currentFileName;
    var fileType = req.body.currentFileType;
console.log('Nom du fichier: ' + fileName + ' ' + 'Type du fichier: ' + fileType);
res.send(fileName + fileType);
});

const port = 5000;

app.listen(port, () => `Server running on port ${port}`);

我希望在 localhost:5000/upload/files 中获取状态数据,但是当我访问 URL 时,我收到消息“无法获取 /upload/files”

有人能帮助我吗 ?谢谢 !

4个回答

您可以使用axios上传文件。

const yourFile = file // Assume this is your file.

现在您需要将其添加到表单数据中。

const formData = new FormData();
formData.append('file', yourFile);

现在:

axios.post('/yourEndpoint', formData).then(res => {
  //Now do what you want with the response;
})

在您的 NodeJS 应用程序中:

app.post('/yourEndpoint', function(req,res){
  fs.readFile(req.files.file.path, function(err, data){
    // Do something with the data (which holds the file information)
  });
});

在你的前端抓取你的文件

 <input type="file" id="inputGroupFile01" 
    onChange={(e) => this.onSelectImageHandler(e.target.files)}
/>

您必须将文件作为 FormData 发送到服务器,如下所示:

onSelectImageHandler = (files) => {
    const file = files[0];
    const formData = new FormData();
    formData.append('file', file)

    const config = {
        headers: {
            "Contetnt-Type":"multipart/form-data" 
        }
    };
}

设置 FormData 后,您可以使用 axios 进行调用。

然后你需要在你的服务器端安装 multer 包 $npm i -S multer,然后在你的 server.js 文件上。

const multer = require('multer');

毕竟需要,您可以在开始时配置multer。

const upload = multer({dest: 'public/uploads/'}).single('file');

然后在您的路线中:

app.post('/upload/files', (req, res) => {
    upload(req,res, (err) => {
        const file = req.file
    const prevUrl = req.body.prevUrl.slice(21) //I use slice to cut the public part of the path, since mine is accessible from anywhere.
    if(!err){
        //here you could add some call to save the prevUrl "url of the file to called it later on your front"
        return User.findOneAndUpdate({_id:req.decoded.userId},{avatarUrl:avatarUrl}, (err, user) => {
            if(!err){       
                return console.log(err)
                })
                return res.json({success:true, message:"File has been successfully uploaded",avatarUrl:"http://localhost:3231/uploads/"+file.filename});
            }
            console.log(err);
        })
    }
    console.log(err);
    })
});

希望能帮助到你。

由于您正在尝试发送文件,因此最好使用 Post(快速提示:当您需要从服务器获取数据时使用 Get,而当您需要将数据发布到服务器时使用 Post)。

然后对于express,你应该看看multer,它是一个用于处理多部分/表单数据的中间件。

最后,在您的react中,您需要使用 fetch 以多部分形式发送文件

这是因为您正在使用app.post.

app.post函数侦听发布请求(不是获取)。

为了让它运行获取请求,您必须使用该app.get功能

IE:-

app.get("/upload/files",(req,res)=>{res./*status(400).*/send("please use a post request")})