node.js - 如何使用 Axios + 文本字段数据发送文件
问题描述
我已经在这个问题上停留了几天,我正因为沮丧而拉扯我的头发。我正在尝试使用 axios 发送文本字段等表单数据以及图像:
前端:
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData();
const img = e.target.files[0];
formData.append("img", img, img.name);
console.log(formData);
this.props.postMe(
{
body: this.state.body,
reqType: this.state.reqType,
location: this.state.location,
},
formData
);
};
<form onSubmit={this.handleSubmit}>
<TextField
name="body"
type="text"
onChange={this.handleChange}
/>
<TextField
name="reqType"
type="text"
onChange={this.handleChange}
/>
<TextField
name="location"
type="text"
onChange={this.handleChange}
/>
<input
type="file"
name="img"
hidden
onChange={this.handleSubmit}
/>
</form>
后端:
exports.postme = (req, res) => {
const newRex= {
body: req.body.body,
reqType: req.body.reqType,
location: req.body.location,
};
const BusBoy = require("busboy");
const path = require("path");
const os = require("os");
const fs = require("fs");
const busboy = new BusBoy({ headers: req.headers });
let imageFileName;
let imageToBeUploaded = {};
busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
if (mimetype !== "image/jpeg" && mimetype !== "image/png") {
return res.status(400).json({ error: "Wrong file type submitted" });
}
const imageExtension = filename.split(".")[filename.split(".").length - 1];
imageFileName = `${Math.round(
Math.random() * 100000000
)}.${imageExtension}`;
const filepath = path.join(os.tmpdir(), imageFileName);
imageToBeUploaded = { filepath, mimetype };
file.pipe(fs.createWriteStream(filepath));
});
busboy.on("finish", () => {
admin
.storage()
.bucket()
.upload(imageToBeUploaded.filepath, {
resumable: false,
metadata: {
metadata: {
contentType: imageToBeUploaded.mimetype,
},
},
})
.then(() => {
const imgUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${imageFileName}?alt=media`;
db.collection("requests")
.add(newRequest)
.then((doc) => {
db.doc(`/requests/${doc.id}`).update({ imgUrl });
const res = newRex;
res.Id = doc.id;
res.imgUrl = imgUrl ;
return res.json(newRex);
});
})
.catch((err) => {
res.status(500).json({ error: "Something went wrong" });
console.error(err);
});
});
busboy.end(req.rawBody);
};
在我的后端,如果我只单独实现上传图像部分,它和文本部分一样工作,但是由于某种原因,当我将图像和文本字段数据组合在一起时它会失败?
非常感谢任何帮助或建议!
解决方案
推荐阅读
- swift - Swift:UITableViewController 选择单元格并将获取的对象传递给 UIViewController
- python - Python 的反应式 DAG 有哪些库?
- c# - 当键值是未知对象时反序列化嵌套的json
- javascript - 访问动态呈现的子状态
- javascript - 使用 queryselector 通过单击更改背景颜色
- javascript - Uncaught SyntaxError: missing ) 在参数列表生成点击事件的动态 HTML 之后
- wordpress-theming - TwentyTwentyOne 儿童主题的最佳实践?
- python - 在 tkinter 中获取用于 sqllite 查询的组合框变量
- angular - Flex包装器调整大小后如何强制ngx-datatable调整大小?
- node.js - Async/await mvc express 使用 .catch() 处理错误的问题