路由Next.js的文件上传不起作用"/>
从API路由Next.js的文件上传不起作用
我正在尝试将文件成功上载到服务器,但是我从中获得了这个控制台输出:
API解析后未发送对/ api / upload的响应,这可能会导致请求停止。
尽管文件已成功放入文件夹。
我不太了解我如何发送关于我的回复。
我在做什么错?
这是我的表单代码:
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
。
更多推荐
从API路由Next.js的文件上传不起作用
发布评论