NodeJS 服务器端 - 文件 Expected UploadFile, received: <class 'str'>

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

从 NodeJs 服务器端上传文件时遇到问题,找到了 100 个帖子并进行了研究,但没有任何效果,将不胜感激。

应用程序的结构

  1. Front App - React Admin 框架接收文件,我在 base64 中编码图像的内容以发送到 API

  2. 后端 - NestJS 应用程序 - 在 API 中接收 base64 图像

  3. 从我的后端 API 需要将文件发送到外部后端(Python API)进行上传 - 这就是问题所在

请看下面我的代码,JS文件有问题

我尝试了几种方法,但都以同样的错误结束

1 解决方案

  • 在缓冲区中转换base64图像并发送到外部后端上传文件
  • 也尝试通过 cleanImageBuffer 但没有变化
import axios from 'axios';
import FormData from 'form-data';

export async function upload(
  fileBase64: string,
  filename: string
): Promise<any> {

  const buffer = Buffer.from(fileBase64, 'base64')
  const extension = fileBase64.substring(fileBase64.indexOf('/') + 1, fileBase64.indexOf(";base64"))
  const cleanBase64 = fileBase64.replace(/^data:image\/png;base64,/, '')
  const cleanImageBuffer = Buffer.from(cleanBase64, 'base64')

  const formData = new FormData();
  // have tried to pass as well cleanImageBuffer but no changes
  formData.append('file', buffer);
  formData.append('fileName', filename + '.' + extension);
  formData.append('namespace', 'test');
  
  return await axios
    .post('external_api_url', JSON.stringify(formData), {
      headers: {
        Authorization: `Bearer token`,
        ContentType: 'multipart/form-data'
      }
    })
    .then((response) => {
      console.log('response = ' + JSON.stringify(response))
    })

结果1解决方案

{
    "status": "error",
    "error": {
        "code": "bad_request",
        "message": "file Expected UploadFile, received: <class 'str'>"
    }
}

2 解决方案

  • 从 base64 图像收到保存在我的磁盘上
  • 创建流并发送图像后
export async function upload (
  fileBase64: string,
  filename: string
): Promise<any> {

  const extension = fileBase64.substring(fileBase64.indexOf('/') + 1, fileBase64.indexOf(";base64"))
  const cleanBase64 = fileBase64.replace(/^data:image\/png;base64,/, '')

  const TMP_UPLOAD_PATH = '/tmp'

  if (!fs.existsSync(TMP_UPLOAD_PATH)) {
    fs.mkdirSync(TMP_UPLOAD_PATH);
  }

  fs.writeFile(TMP_UPLOAD_PATH + '/' + filename + '.' + extension, cleanBase64, 'base64', function(err) {
    console.log(err);
  })

  const fileStream = fs.createReadStream(TMP_UPLOAD_PATH + '/' + filename + '.' + extension)

  const formData = new FormData();
  formData.append('file', fileStream, filename + '.' + extension);
  formData.append('fileName', filename + '.' + extension);
  formData.append('namespace', 'test');

  return await axios
    .post('external_api_url', formData, {
      headers: {
        Authorization: `Bearer token`,
        ContentType: 'multipart/form-data'
      }
    })
    .then((response) => {
      console.log('response = ' + JSON.stringify(response))
    })
}

结果2解决方案

{
    "status": "error",
    "error": {
        "code": "bad_request",
        "message": "file Expected UploadFile, received: <class 'str'>"
    }
}

以相同结果结束的其他解决方案

  • 尝试使用从节点获取中获取 - 结果相同
  • 发现有些人使用的 axios 版本过时并遇到此问题,我安装了最新的 axios 1.1.3 版本但结果相同

我需要的最佳场景

  • 从接收到的base64图像
  • 在缓冲区中转换并将文件发送到外部 Python API,以避免将文件保存在本地磁盘上

将不胜感激

下面是一个有效但不是 JS 的 python 示例(JS 无效)

import requests

url = "http://127.0.0.1:8000/external_api"

payload={'namespace': 'test'}
files=[
  ('file',('lbl-pic.png',open('/local/path/lbl-pic.png','rb'),'image/png'))
]
headers = {
  'Authorization': 'Bearer token'
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

print(response.text)
node.js file-upload axios server-side image-upload
2个回答
1
投票

只是一个建议:

  1. 首先看看您是否可以使用常规 HTML 文件输入(不要使 Base64 复杂化),如此处所述https://stackoverflow.com/a/70824288/2347084
  2. 如果 (1) 有效,则尝试按照此处的建议将 base64 转换为 File 对象https://stackoverflow.com/a/47497249/2347084
  3. 结合(2)和(1)

0
投票

我想发布我的解决方案,因为正如我在互联网上看到的那样,每个人都对

FormData
有问题
nodejs

  1. 我正在使用
    axios
    发送用于上传文件的缓冲区
  2. 问题是
    axios
    ,特别是
    FormData
    ,它不会在标题中添加
    Content-Length
    ,任何版本的axios都不会这样做
  3. python API 需要
    Content-Length

如果此标头在 python API 中变为可选,则代码开始工作

解决方案是如果有人有类似的问题

  • axios 在使用
    Content-Length
    时不添加
    FormData
    (找不到任何可用的 axios 版本)
  • 如果您在没有文件在本地磁盘上的情况下使用缓冲区,那么会因为
    Content-Length
  • 而出现问题
  • 如果你在本地有文件而不是使用模块 fs,你就可以读取文件并添加所有标题和 Content-Length

在 axios GitHub 问题上说这个错误在最新的 axios 中已修复,但在我的情况下它仍然不起作用

下面是使用缓冲区的代码,第三个 API 不需要 Content-Length

    function upload (image: {imageBase64: string, fileName: string}) {
      const { imageBase64, fileName } = image;
      const cleanBase64 = imageBase64.substr(imageBase64.indexOf(',') + 1);
      // buffer should be clean base64
      const buffer = Buffer.from(cleanBase64, 'base64');
    
      const formData = new FormData();
      // filename as option is required, otherwise will not work, will say that received file is string and UploadFile
      formData.append('file', buffer, { filename: fileName });
    
      return client
        .post('url', formData, {
          headers: {
            ...formData.getHeaders(),
          },
        })
        .then((response) => response.data)
        .catch((error) => {
          return {
            status: 'error',
            error,
          };
        });
    }
© www.soinside.com 2019 - 2024. All rights reserved.