i have a project and i am trying to send an image to the API. the curl for API endPoint is as follows:
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"'
now this API will accept an image. now i am taking an image from user like this:
<input
type="file"
name="image"
onChange={event => {
handleImageChange(event);
setFieldValue("image", event.currentTarget.files[0]);
}}
/>
and then i am trying to pass it to formData as i want to convert the image into the content type that is needed by the 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
};
here you can see when i am consoling file i am getting the input file of image this is what it looks like in console:
file {name: 'Mind map.png', lastModified: 1684153465349, lastModifiedDate: Mon May 15 2023 17:24:25 GMT+0500 (Pakistan Standard Time), webkitRelativePath: '', size: 315013, …}
but when i am passing it to formData and trying to console the formData it is an empty object like this :
formData FormData {}
can you tell me the problem.
this my action and when i am calling from 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());
}
}
. and this is my API call:
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
});
};