gpt4 book ai didi

javascript - 如何在 React 中使用 fetch 方法上传文件?

转载 作者:行者123 更新时间:2023-12-02 21:10:09 28 4
gpt4 key购买 nike

我正在开发一个 React 组件,我想将 Excel 文件上传到服务器。这就是我正在尝试的。但当我控制台请求正文时,它给了我一个空对象

<input type="file" id="avatar" name="avatar" onChange={this.fileHandler.bind(this)} style={{"padding":"10px"}}/>

这是文件处理程序方法,当输入文件更改时将执行:

fileHandler = (event) => {
event.preventDefault();
let fileObj = event.target.files[0];
console.log(fileObj);
//console.log(JSON.stringify(fileObj));

var data = new FormData()
data.append('file', fileObj)

fetch("/upload", {
method: 'POST',
body: data
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.text();
}).then(function(data) {
console.log(data)
}).catch(function(err) {
console.log(err)
});
}

这是上传文件的服务器代码。

app.post('/upload', function(req, res) {
console.log(req.body); // Output : {} or undefined
/*try {
if(!req.files) {
res.send({
status: false,
message: 'No file uploaded'
});

} else {
let avatar = req.files.avatar;

//Use the mv() method to place the file in upload directory (i.e. "uploads")
avatar.mv('./uploads/' + avatar.name);

//send response
res.send({
status: true,
message: 'File is uploaded',
data: {
name: avatar.name,
mimetype: avatar.mimetype,
size: avatar.size
}
});
}
} catch (err) {
res.status(500).send(err);
}*/
})

如果我在下面尝试使用表单操作,它会在 req.files 中提供正确的输出,但我不想重定向。

<form id="myForm" method="post" encType="multipart/form-data" action="/upload">
<input type="hidden" name="msgtype" value="2"/>
<input type="file" id="avatar" name="avatar" onChange={this.fileHandler.bind(this)} style={{"padding":"10px"}}/>
<input type="submit" value="Upload" />
</form>

此外,我不想使用 axios,因为我对所有其他执行使用相同的获取请求。如有任何帮助,我们将不胜感激。

最佳答案

最后,我能够使用 fetch 处理正确的请求参数。这是我尝试过并按预期工作的解决方案:

<form id="myForm" method="post" encType="multipart/form-data" action="/upload" onSubmit={this.fileSubmit.bind(this)}>
<input type="hidden" name="msgtype" value="2"/>
<input type="file" id="avatar" name="avatar" onChange={this.fileHandler.bind(this)} style={{"padding":"10px"}}/>
<input type="submit" value="Upload" />
</form>

这是提交处理程序:

fileSubmit = (event) => {
event.preventDefault();
fetch(event.target.action, {
method: 'POST',
body: new FormData(event.target) // event.target is the form

}).then((resp) => {
return resp.json();
//console.log(resp.json());

}).then((body) => {
// TODO handle body
console.log(body);
if(body.status) {
alert(body.message);
}
else {
alert("Please Select a file to upload");
}
}).catch((error) => {
// TODO handle error
//
});

在服务器端,我可以获得req.files以及req.body

app.post('/upload', function(req, res) {
console.log(req.body); // which gives me form data
console.log(req.files); // which gives me file object
});

关于javascript - 如何在 React 中使用 fetch 方法上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61120850/

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