gpt4 book ai didi

node.js - 从 API 路由 Next.js 上传文件不起作用

转载 作者:行者123 更新时间:2023-12-05 07:11:41 25 4
gpt4 key购买 nike

我正在尝试将一个文件上传到我的服务器,我可以使用我的代码成功完成该操作,但我从中得到了一个控制台输出:

API resolved without sending a response for /api/upload, this may result in a stalled requests.

不过文件已经成功放入文件夹了。

我不太明白为什么我没有发送关于我自己的回复。

我做错了什么?

这是我的表单代码:

const axios = require("axios").default;

class VideoUploadForm extends React.Component {
constructor(props) {
super(props);
this.state = {
file: null,
uploaded: false
};
}

onChangeHandler = event => {
this.setState({
selectedFile: event.target.files[0],
loaded: 0
});
};

onClickHandler = () => {
const data = new FormData();
data.append("video", this.state.selectedFile);
axios
.post("/api/upload", data, {
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
};

render() {
return (
<div>
<form
action="#"
method="post"
encType="multipart/form-data"
target="transFrame"
>
<input type="file" name="video" onChange={this.onChangeHandler} />
<button onClick={this.onClickHandler}>upload</button>
</form>
<iframe
width="200"
height="100"
name="transFrame"
id="transFrame"
></iframe>
</div>
);
}
}

export default VideoUploadForm;

和API

import multer from "multer";

export const config = {
api: {
bodyParser: false
}
};

var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "public");
},
filename: function(req, file, cb) {
cb(null, "video.mp4");
}
});

var upload = multer({ storage: storage });

export default async (req, res) => {
upload.single("video")(req, {}, err => {
res.send(req.file.path);
res.end();
console.log(req.file); // do something with the file
});
};

最佳答案

这就是问题所在

res.send(req.file.path);
res.end();

res.send 隐式调用 res.write 后跟 res.end。您应该删除第二个 res.end

关于node.js - 从 API 路由 Next.js 上传文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60673861/

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