【问题标题】:How do I upload an array of mages using fect API如何使用 fetch API 上传图像数组
【发布时间】:2021-03-25 20:48:57
【问题描述】:

我正在尝试使用我的自定义 API(Node JavaScript)上传一组图像,在这里我只想将文件名保存到我的数据库中,并且文件的上传工作正常(我为上传创建的中间件工作得很好,因为我尝试在 postman 中使用相同的中间件)。

当涉及到实际的 JavaScript 文件时,它不起作用并显示以下错误:

值“{'0':{},'1':{}}”在路径“images”处转换为字符串失败,图像:值“[ {'0':{},转换为数组失败, '1': {} } ]" 在路径“图像”

这是我的代码

const createProperty = ['city', 'propertyType', 'propertyName', 'images'];

const newProperty = new Array();
for (var i = 0; i < myids.length; i++) {
  newProperty[i] = $(myids[i]).val();
}


newProperty[myids.length] = [document.getElementById('PropertyPhotos').files];

const data = {};
createProperty.forEach((id, index) => {
  data[createProperty[index]] = newProperty[index]
})


await createData(data);

// here is the CreateDate function

export const createData = async (data) => {
  try {
    const res = await axios({
      method: 'POST',
      url: '/api/v1/properties',
      data
    });

    if (res.data.status === 'success') {
      showAlert('success', 'Property Created Successfully');
    }
    console.log(res.data);
  } catch (err) {
    showAlert('error', err.response.data.message);
    console.log(err.response.data.message);
  }
}        

【问题讨论】:

  • 我认为您应该使用 JSON.stringify 将对象转换为字符串。
  • newProperty 和 document.getElementById('PropertyPhotos').files 的值是多少?您想插入/复制图像文件并从中获取二维数组吗?请使用控制台日志或调试器来确定问题出现的位置并发布代码的预期行为
  • 迭代时myids中有什么?请在您的代码中显示。

标签: javascript node.js arrays asynchronous fetch-api


【解决方案1】:

看起来您正在使用 Mongo。看看herehere

要发送文件,您需要使用表单数据,但我在您的代码中没有看到它。

const formdata = new FormData();

formdata.append("file", fileInput.files[0], "/filepath.pdf");

【讨论】:

  • 你好,我不知道,但每当我使用 formdata 时,我上面的函数 createData 无法正常工作,就像它给我 null 作为数据一样。请帮助我
  • @AshishArjun 显示前后数据传输的完整代码
猜你喜欢
  • 2018-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-15
  • 2019-02-02
  • 2017-06-01
相关资源
最近更新 更多