gpt4 book ai didi

javascript - 无法使用 Multer 将文件从 React 上传到 Express(req.file 不显示任何内容,req.body 没问题)

转载 作者:行者123 更新时间:2023-12-03 22:33:37 25 4
gpt4 key购买 nike

我有几天的问题,如何通过reactjs 发送文件,通过sequelizing ORM 来表达和存储在mysql 中。我使用两个单独的文件夹 arhiva-backend 和 arhiva-frontend,它们由 CORS 连接。我设法通过 formData 发送并将 req.body 中的所有内容插入数据库,但 req.file 根本不起作用。请帮忙。
这是我的 reactjs 文件。我正在使用 ExpressJs、React 最新版本、Sequelize ORM、phpmyadmin (mysql) 来存储数据。

import React, {Component} from 'react';
import DashboardSideBar from '../components/DashboardSideBar';
import DashboardHeader from '../components/DashboardHeader';
import CreateDosijeForm from '../components/forms/CreateDosijeForm';
// import axios from 'axios';

class CreateWorkerDosije extends Component{

constructor (props){
super (props);

this.state = {
data:{
firstName:'',
lastName:'',
dosijeNum:'',
jmbg:'',
uploadedFile:'',

},


}
this.changeData = this.changeData.bind(this);
this.onSubmitData = this.onSubmitData.bind(this);
}

changeData(e) {
switch(e.uploadedFile){
case "uploadedFile":
this.setState({ uploadedFile: e.target.files[0] });
break;
default:

const field = e.target.name;
const data = this.state.data;
data[field] = e.target.value;

this.setState({
data
});

}
}

onSubmitData = (e) => {
e.preventDefault();
// const data = this.state.data;
const formData = new FormData();
formData.append('uploadedFile',this.state.uploadedFile);
formData.append('firstName', this.state.data.firstName);
formData.append('lastName', this.state.data.lastName);
formData.append('dosijeNum', this.state.data.dosijeNum);
formData.append('jmbg', this.state.data.jmbg);
fetch("http://localhost:5000/api/upload",{
method:"POST",
body:(
formData
),
})
.then(res => res.json())
.catch((error )=> {
console.log(error)
});



}



render() {
return(

<div id = "create-dosije-form">
<DashboardSideBar/>
<div className="dashboard-body">
<DashboardHeader/>

</div>

<div className="dashboard-content">
<div className="headline filter primary">
<h4> Unesi novi dosije </h4>
</div>


<CreateDosijeForm
data = {this.state.data}
onChange = {this.changeData}
onSubmit = {this.onSubmitData}
/>
</div>



</div>


)
}


}

export default CreateWorkerDosije;
这是表格
import React from 'react';


const CreateDosijeForm = ({

onSubmit,
onChange,
data

}) => (
<div>
<form id="departman-form" onSubmit = {onSubmit} encType = "multipart/form-data">
<label htmlFor="firstName" className="rl-label required">Ime</label>
<input type="text" id="firstName" name="firstName" value = {data.firstName} placeholder="Unesite ime radnika" onChange={onChange}/><br/>
<label htmlFor="lastName" className="rl-label required">Prezime</label>
<input type="text" id="lastName" name="lastName" value = {data.lastName} placeholder="Unesite ime radnika" onChange={onChange}/><br/>
<label htmlFor="dosijenum" className="rl-label required" >Broj dosijea</label><br/>
<input type="text" pattern = "[0-9]*" id="dosijenum" name="dosijeNum" value = {data.dosijeNum} placeholder="Unesite broj dosijea" onChange={onChange}/><br/>

<label htmlFor="jmbg" className="rl-label required">JMBG/PIO/LBO</label><br/>
<input type="number" id="jmbg" name="jmbg" value = {data.jmbg} placeholder="Unesite JMBG/PIO/LBO broj radnika" onChange={onChange}/><br/>
<label htmlFor="file" className="rl-label required">Izaberite fajlove</label><br/>
<input type="file" id="uploaded_file" name="uploadedFile" value = {data.uploadedFile} placeholder="Unesite dokumenta" multiple/><br/>

<button className="button mid dark">Sačuvaj</button>
<p className="rl-label required">Polja oznacena sa zvezdicom su obavezna polja</p>
</form>



</div>
);

export default CreateDosijeForm;


express 代码
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const cors = require('cors')
// const router = express.Router();

const app = express();
// console.log(port)

const sequelize = require ('./config/database');
const Dosije = require('./models/dosije');

let corsOptions = {
origin: "http://localhost:5000"
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(cors(corsOptions));
app.use((req,res,next)=>{
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type', 'Authorization');
next();
})


sequelize.sync().then(result => {
// console.log(result)
try {
sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
});

//Set Storage engine
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './public/uploads/')
},
filename: function(req,file,cb) {
cb(null, file.fieldname + '-' + Date.now() + Path2D.extname(file.originalname));
}
});

//init upload

const upload = multer({storage});



app.post('/api/upload', upload.single('uploadedFile'), (req, res, next) => {
console.log(req.file)
console.log(req.body)
const file = (req.file)

if (!file) {
const error = new Error('Please upload a file')
return next(error)
}


const firstName = req.body.firstName;
const lastName = req.body.lastName;
const dosijeNum = req.body.dosijeNum;
const jmbg = req.body.jmbg;
const uploadedFile = req.file
Dosije.create({
dosijeNum: dosijeNum,
firstName: firstName,
lastName: lastName,
JMBG: jmbg,
docs: uploadedFile
})
.then(res=>{
console.log(res)})
.catch(err => {
console.log(err);
})
res.send();
next();


})



const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server listening on port ${port}`));

模型
const Sequelize = require ('sequelize');

const sequelize = require ('../config/database');
const Dosije = sequelize.define('dosije', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
dosijeNum:{
type: Sequelize.STRING,
},
firstName:{
type: Sequelize.STRING,

},
lastName: {
type: Sequelize.STRING,
},
JMBG: {
type: Sequelize.INTEGER,

},
docs: {
type: Sequelize.STRING
},

});

module.exports = Dosije;

最佳答案

前端:
改变这个:

<input type="file" id="uploaded_file" name="uploadedFile" value = {data.uploadedFile} placeholder="Unesite dokumenta" multiple/><br/>
对此:
<input type="file" name="file">
后端:
改变这个:
upload.single('uploadedFile')
对此:
upload.single('file')

关于javascript - 无法使用 Multer 将文件从 React 上传到 Express(req.file 不显示任何内容,req.body 没问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64144778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com