redux 将文件传递给formData时得到空对象

idfiyjo8  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(158)

我有一个项目,我试图发送一个图像的API。API endPoint的curl如下:

curl --location 'https://do-rider.cheetay.pk/alerts/image' \
--header 'Authorization: Token a24ffbda2317e9b41ce227856e0603b7c7666ccc ' \
--form 'image=@"/home/abdul/Pictures/Screenshots/Screenshot from 2023-04-01 02-37-29.png"'

现在这个API将接受一个图像。现在我从用户那里得到一个像这样的图像:

<input
          type="file"
          name="image"
          onChange={event => {
            handleImageChange(event);
            setFieldValue("image", event.currentTarget.files[0]);
          }}
        />

然后我试图将其传递给formData,因为我想将图像转换为API所需的内容类型。

const handleImageChange = event => {
    const file = event.currentTarget.files[0];
    setSelectedImage(file);
    console.log("file", file);
    debugger;
    const formData = new FormData();
    formData.append("image", file);
    console.log("formData", formData);
    debugger;
    sendImageAttempt(formData); // Call sendImageAttempt function with FormData object
  };

在这里你可以看到当我在consoling文件时,我正在获取图像的输入文件,这是它在consoling中的样子:

file {name: 'Mind map.png', lastModified: 1684153465349, lastModifiedDate: Mon May 15 2023 17:24:25 GMT+0500 (Pakistan Standard Time), webkitRelativePath: '', size: 315013, …}

但是当我将它传递给formData并试图控制formData时,它是一个像这样的空对象:

formData FormData {}

请告诉我问题所在。
这是我的行动,当我从 Saga 打电话:

export const sendImageAttempt = data => ({
  type: types.SEND_IMAGE_ATTEMPT,
  data
});

my Saga middleware:

import { call, put } from "redux-saga/effects";
import { toast } from "react-toastify";
import { actions } from "../../actions/alerts";
import { sendImageAlertAPI } from "../../api/alerts";
import { logger } from "../../utils";

export function* sendImageAttemptSaga({ data }) {
  try {
    console.log("data for api", data);
    debugger;
    const resp = yield call(sendImageAlertAPI, data); // Send the data directly to the API
    debugger;
    if (resp) {
      yield put(actions.sendImageSuccess(resp));
      toast.success("Alert sent");
    } else {
      yield put(actions.sendImageFailure(""));
    }
  } catch (error) {
    logger.error(error);
    yield put(actions.sendImageFailure(error));
    toast.error(error.toString());
  }
}

这是我的API调用:

export const sendImageAlertAPI = data => {
  console.log("data in apicaller", data);
  debugger;
  apiCaller({
    method: REQUEST_TYPES.POST,
    url: ENDPOINTS.SEND_IMAGE,
    contentType: "multipart/form-data",
    data
  });
};
gopyfrb3

gopyfrb31#

你不能直接console.log一个formData来查看追加项,使用本问题中回答的方法来实现:
How to inspect FormData?

相关问题