eidellev / inertiajs-adonisjs

279 stars 17 forks source link

File upload problem witn react, inertia and adonis #52

Closed dmostafiz closed 2 years ago

dmostafiz commented 2 years ago

Hello, i am just started with inertia react and adonis js. it seems everything okay, but when i am trying to upload file following inertia js official documentation i found and error like

"index.js:1 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'toString')"

and from the controller i am not getting any file reference to work with. if i am wrong anywhere to implement that, please guide me.

eidellev commented 2 years ago

Hi @dmostafiz Thanks for reporting this issue. I will check it out.

dmostafiz commented 2 years ago

Thanks for your reply, i hope the issue will be solved soon.

eidellev commented 2 years ago

After looking into the issue it seems to be a problem with Inertia's file upload documentation for react. This worked for me:

import React from 'react';
import { useForm } from '@inertiajs/inertia-react';

export const UserForm = function () {
  const { data, setData, post, progress } = useForm<{ name: string; avatar: File }>({
    name: undefined,
    avatar: undefined,
  });

  function submit(e) {
    e.preventDefault();
    post('/users');
  }

  return (
    <form onSubmit={submit}>
      <input
        type="text"
        value={data.name || ''}
        onChange={(e) => setData('name', e.target.value)}
      />
      <input type="file" onChange={(e) => setData('avatar', e.target.files[0])} />
      {progress && (
        <progress value={progress.percentage} max="100">
          {progress.percentage}%
        </progress>
      )}
      <button type="submit">Submit</button>
    </form>
  );
};

The main issue seems to be that you can't assign a value to a file input.

This is how I handled it on the backend:

Route.post('/users', async ({ request, inertia }) => {
  const avatar = request.file('avatar');

  if (avatar) {
    await avatar.move(Application.tmpPath('uploads'));
  }

  return inertia.redirectBack();
});

Feel free to reopen this issue if you run into additional problems.

dmostafiz commented 2 years ago

I am doing same. just one different thing is i am not using typeScript in react.

But i am getting null in the controller endpoint.

Console log Screenshot 2022-02-19 230536

React Component Screenshot 2022-02-19 230618

Controller Screenshot 2022-02-19 230719