【问题标题】:File Upload from API Routes Next.js not working从 API Routes Next.js 上传文件不起作用
【发布时间】:2020-03-13 16:15:16
【问题描述】:

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

在未发送 /api/upload 响应的情况下解析 API,这可能会导致请求停止。

文件已成功放入文件夹中。

我不太明白为什么我没有像我一样发送回复。

我做错了什么?

这是我的表单代码:

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
  });
};

【问题讨论】:

    标签: node.js reactjs video file-upload next.js


    【解决方案1】:

    这就是问题所在

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

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

    【讨论】:

    • 所以我尝试了这个,但是我仍然遇到同样的错误,您是否看到任何其他潜在问题。这可能是我在表单中处理 POST 请求的方式吗?
    【解决方案2】:

    试试

    var upload = multer(storage);
    

    【讨论】:

      猜你喜欢
      • 2018-06-20
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 2020-02-25
      • 2017-01-21
      • 2020-06-13
      • 2017-09-17
      • 2018-10-13
      相关资源
      最近更新 更多