如何发布本地 ZIP 文件?

问题描述 投票:0回答:1

我尝试使用 axios 将本地 zip 文件发布到端点,以便在主线程的异步代码中使用。 使用 Postman 顺利投递。 端点接受文件和哈希值作为 str。

static async sendConf() {
    const dataFolder =
      process.env.NODE_ENV === 'development'
        ? path.join(__dirname, '../../data')
        : path.join(app.getPath('userData'), '/data');
    await Utilities.zipDirectory(
      dataFolder,
      path.join(dataFolder, 'conf.zip'),
    ).then(async (r) => {
      const fs = require('fs');
      const form_data = new FormData();
      fs.readFile(path.join(dataFolder, 'conf.zip'), async (error, data) => {
        form_data.append('hash', TOKEN);
        const bb = new Blob([data]);
        form_data.append('file', bb, {
          contentType: 'multipart/form-data',
          filename: 'conf.zip',
        });

        const response = await Utilities.postAxios('upload-conf', {
          data: form_data,
        })
          .then((r) => {
            console.log(`done`);
          })
          .catch((e) => {
            console.log(`sendConf err : ${e}`);
          });
        console.log(`sendConf : ${response}`);
      });
    });
  }

postAxios 看起来像这样:

static async postAxios(url, params) {
    const obj = await Utilities.readConfFile('settings');
    const authAxios = axios.create({
      baseURL: obj.generalSettings.warehouse,
    });
    try {
      const { data } = await authAxios.post(
        url,
        { ...params },
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        },
      );
      return data;
    } catch (error) {
      console.log(error);
    }
  }

出现以下错误,有什么帮助吗?

TypeError: source.on is not a function
    at Function.DelayedStream.create (/project/node_modules/delayed-stream/lib/delayed_stream.js:33:10)
    at FormData.CombinedStream.append (/project/node_modules/combined-stream/lib/combined_stream.js:45:37)
    at FormData.append (/project/node_modules/form-data/lib/form_data.js:75:3)
    at FormData.defaultVisitor (/project/node_modules/axios/lib/helpers/toFormData.js:175:14)
    at each (/project/node_modules/axios/lib/helpers/toFormData.js:198:73)
    at Object.forEach (/project/node_modules/axios/lib/utils.js:267:10)
    at build (/project/node_modules/axios/lib/helpers/toFormData.js:197:11)
    at toFormData (/project/node_modules/axios/lib/helpers/toFormData.js:214:3)
    at Object.transformRequest (/project/node_modules/axios/lib/defaults/index.js:84:16)
    at transform (/project/node_modules/axios/lib/core/transformData.js:22:15)
    at Axios.request (/project/node_modules/axios/lib/core/Axios.js:45:41)
    at async Function.postAxios (/project/src/main/utilities.ts:114:24)
    at async /project/src/main/utilities.ts:297:26

使用 Electron 26.2.1 和 axios 1.7.7 将本地文件发布到端点 API

reactjs node.js axios electron form-data
1个回答
0
投票

出现您所看到的错误(TypeError:source.on 不是函数)是因为 Axios 在处理文件上传时需要 Node.js 可读流,但正在提供 Blob(通常在浏览器环境中使用)。以下是如何使用 Node.js fs 流来修复代码

const fs = require('fs');
const form_data = new FormData();
const filePath = path.join(dataFolder, 'conf.zip');

fs.readFile(filePath, async (error, data) => {
  if (error) {
    console.error("Error reading file:", error);
    return;
  }

  // Append hash
  form_data.append('hash', TOKEN);

  // Create a read stream and append it directly
  const fileStream = fs.createReadStream(filePath);
  form_data.append('file', fileStream, 'conf.zip');

  try {
    const response = await Utilities.postAxios('upload-conf', form_data);
    console.log(`sendConf : ${response}`);
  } catch (e) {
    console.log(`sendConf err : ${e}`);
  }
});

static async postAxios(url, formData) {
  const obj = await Utilities.readConfFile('settings');
  const authAxios = axios.create({
    baseURL: obj.generalSettings.warehouse,
  });
  
  try {
    const { data } = await authAxios.post(url, formData, {
      headers: {
        ...formData.getHeaders(), // Important: Axios uses these headers for multipart
      },
    });
    return data;
  } catch (error) {
    console.log(error);
    throw error;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.