我需要在 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 !"
});
}
Run Code Online (Sandbox Code Playgroud)
}
和我的 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}`);
Run Code Online (Sandbox Code Playgroud)
我希望在 localhost:5000/upload/files 中获取状态数据,但是当我访问 URL 时,我收到消息“无法获取 /upload/files”
有人能帮助我吗 ?谢谢 !
您可以使用axios上传文件。
const yourFile = file // Assume this is your file.
Run Code Online (Sandbox Code Playgroud)
现在您需要将其添加到表单数据中。
const formData = new FormData();
formData.append('file', yourFile);
Run Code Online (Sandbox Code Playgroud)
现在:
axios.post('/yourEndpoint', formData).then(res => {
//Now do what you want with the response;
})
Run Code Online (Sandbox Code Playgroud)
在您的 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)
});
});
Run Code Online (Sandbox Code Playgroud)
在你的前端抓取你的文件
<input type="file" id="inputGroupFile01"
onChange={(e) => this.onSelectImageHandler(e.target.files)}
/>
Run Code Online (Sandbox Code Playgroud)
您必须将文件作为 FormData 发送到服务器,如下所示:
onSelectImageHandler = (files) => {
const file = files[0];
const formData = new FormData();
formData.append('file', file)
const config = {
headers: {
"Contetnt-Type":"multipart/form-data"
}
};
}
Run Code Online (Sandbox Code Playgroud)
一旦你完成了 FormData 设置,你就可以使用 axios 进行调用。
然后你需要在服务器端 $npm i -S multer 安装 multer 包,然后在你的 server.js 文件上安装。
const multer = require('multer');
Run Code Online (Sandbox Code Playgroud)
您可以在满足所有要求后在开始时配置 multer。
const upload = multer({dest: 'public/uploads/'}).single('file');
Run Code Online (Sandbox Code Playgroud)
然后在你的路线中:
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);
})
});
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
8267 次 |
| 最近记录: |