1

I am trying to upload a picture, send the picture by the front end (axios request), and then this error is returned by the server.

Cannot deserialize the current JSON array into type 'Microsoft.AspNetCore.Http.IFormFile' because the type requires a JSON object to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path 'file', line 1, position 339."

    [HttpPost("add")]
    public async Task<IActionResult> Add(Post post, IFormFile file){............}

this is my axios request

  const submit = useCallback(
    async (values: PostExtensions) => {
      debugger;
      setLoading(true);

      const tarih = dayjs(values.date);
      values.tarih = dayjs(date, "YYYY-MM-DDTHH:mm:ss Z").format();

      const formdata = new FormData();
      formdata.append("postId", values.postId!);
      formdata.append("file", values.file![0]);
      formdata.append("userId", values.userId!);
      formdata.append("projectId", values.projectId!);
      formdata.append("date", values.date!);

      await entitySubmit({
        values: JSON.parse(JSON.stringify(values)),
        dispatch: dispatch,
        returndata: true,
        headers: {
          "Content-Type": "multipart/form-data"
        },
        links: [
          {
            type: 0,
            link: "post/addpost",
            actionType: ActionType.add_Post,
            method: "POST",
          },
          {
            type: 1,
            link: "post/editpost",
            actionType: ActionType.edit_Post,
            method: "POST",
          },
        ],
        id: "postId",
      });
      return null;
    },
    [show, dispatch]
  );

when I tried to post formdata, It does'nt submit.

EDIT 1: I found the problem where is, formData send null file object something like this

formdata.get('file') // '[Object object]'
5
  • first try to hit that api from postman or any api tester software then move for consuming that api in frontend language. Commented Jul 9, 2020 at 16:14
  • How can I test posting image file on postman or whatever ? Commented Jul 9, 2020 at 16:16
  • Can you show the axios code that is uploading the file? From the error, I would guess you are trying to post it as JSON and it should be posted as a multi-part upload Commented Jul 9, 2020 at 16:18
  • When I tried content type of multi-part form data, I got this error "Failed to read the request form. Missing content-type boundary." Commented Jul 9, 2020 at 16:23
  • test in postman stackoverflow.com/questions/55093843/… Commented Jul 9, 2020 at 17:12

1 Answer 1

0

Not a direct answer to your question, but I've found that sending files via ajax is often times much easier when using base64 encoding. Here's a small sample of how you can achieve this:

//client side
//this function converts a file object to a base64 string
const toBase64 = file => new Promise((resolve, reject) => {
   const reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = () => resolve(reader.result);
   reader.onerror = error => reject(error);
});

document.getElementById("upload").onclick = async () => {
    const file = document.getElementById('myfile').files[0];
    const base64 = await toBase64(file);
    const response = await fetch('/home/upload', {
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify( {base64 /*add any additional values you need here */})
})
    const json = await response.json();
}

//server side
public class UploadData
{
    public string Base64Data { get; set; }
    //any additional properties you need here....
}

[HttpPost]
public IActionResult Upload([FromBody]UploadData data)
{
    var base64 = data.Base64Data.Substring(data.Base64Data.IndexOf(",") + 1); //bit of a hack, need to remove the additional part of the base64 string that JS generates but that .net doesn't like
    var bytes = Convert.FromBase64String(base64);
    //bytes is now available to do whatever you need with
    return Json(someObjectYouWantToReturn);
}

Hopefully this code will be a good enough starting point to get you where you need. Again, base64 might not be what you're after, but I use this approach a lot, I find it simple to deal with personally.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.