0

我需要从页面上的 HTML 表单发送文件

<input id="file" name="file" type="file" data-file-accept="pdf" data-component="fileupload">

到外部API,其中文件参数如下:

Parameter name: file
Example values: @file_name.jpg;type=image/jpeg
Description: Filename with filepath

提供 cURL 示例:

curl -X POST "..."
    -H "accept: application/json"
    -H "Authorization: Bearer mytoken1234"
    -H "Content-Type: multipart/form-data"
    -F "file[file]=@test.pdf;type=application/pdf"
    -F "dictionary_file_type=CV"
    -F "file[isPublic]=1"

该页面是 Jamstack 页面,没有标准服务器,唯一的“后端”选项是无服务器 AWS lambda 函数(确切地说是用节点编写的 Netlify 函数)。有没有使用 node.fetch 或 axios 发送此文件的方法?或其他适用于此的工具?

也许我上面所说的工作功能的例子会有所帮助:

axios

const axios = require("axios");
const FormData = require("form-data");
const form = new FormData();

form.append("client_id", "...")
form.append("client_secret", "...")
... // rest of data

exports.handler = async (event) => {
  try {
    const res = await axios.post(url, form, { headers: ... });
    return { statusCode: 200, body: JSON.stringify(res) };
  } catch (err) {
    return { statusCode: 400, body: JSON.stringify(err.message) };
  }
};

节点获取

const fetch = require('node-fetch');

const myHeaders = new fetch.Headers();
myHeaders.append(...);

exports.handler = async (event, context) => {
  let response;

  const data = { name: "New", lastname: "Candidate" };

  const requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: JSON.stringify(data)
  };

  try {
    response = await fetch(endpoint, requestOptions)
      .then(response => response.json())
      .then(data => console.log(data))
      .catch((err) => console.log(err);
  } catch (err) {
    return { statusCode: 500, body: JSON.stringify({error: err.message}) };
  }
  return { statusCode: 200, body: JSON.stringify({data: res}) }
};

4

0 回答 0