How to upload files on the front-end (in React) and send them to the backend (Laravel/API)?

Viewed 241

I'm trying to host some files received via input in my application in the cloud, but I'm having trouble sending the information from the front-end to the back-end. Technologies used: Front-end: ReactJs (TypeScript), MaterialUi, StyledComponents Back-end: REST API (Washable)

I'm using a FormData to receive the parameters and pass them to the back-end (which is working perfectly, because in the tests done in insomnia the images go to the cloud):

export default function ModalAnexo(props: ModalAnexoProps) {

  const [cnh, setCnh] = useState('');
  const [cpf, setCpf] = useState('');
  const [rg, setRg] = useState('');

    function salvaranexo(e: FormEvent) {
    e.preventDefault();

    const AnexoData = new FormData();
    AnexoData.append('cnh', cnh);
    AnexoData.append('cpf', cpf);
    AnexoData.append('rg', rg);

    baseUrl
      .post('/anexo/store', AnexoData, {
        headers: { 'Content-Type': 'multipart/form-data', 'Accept':'application/json' },
      })
      .then(() => {
        callModel('Sucesso', 'Cadastro realizado com sucesso.', 'Ok');
        setOpen(false);
      })
      .catch((error) => {
        callModel('Erro', 'Ocorreu um erro', 'OK');
      });
  }

  <form onSubmit={salvaranexo}>
      <DialogTitle id="alert-dialog-title">{'Inserir arquivos:'}</DialogTitle>
      <DialogContent
        style={{
          display: 'grid',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'center',
          flexWrap: 'wrap',
          gap: '1.3rem',
        }}
      >
        <div>
          <TextField
            id="cnh"
            value={cnh}
            onChange={(e) => setCnh(e.target.value)}
            label="CNH Frente"
            type="file"
            variant="outlined"
            inputProps={{ accept: '.png, .pdf, .jpg, .jpeg' }}
            InputLabelProps={{
              shrink: true,
            }}
          ></TextField>
          <IconButton
            onClick={function resetaCNH() {
              setCnh('');
            }}
            aria-label="delete"
          >
            <DeleteIcon />
          </IconButton>
        </div>
        <div>
          <TextField
            id="cnh2"
            value={cnh2}
            onChange={(e) => setCnh2(e.target.value)}
            label="CNH Verso"
            type="file"
            variant="outlined"
            inputProps={{ accept: '.png, .pdf, .jpg, .jpeg' }}
            InputLabelProps={{
              shrink: true,
            }}
          ></TextField>
          <IconButton
            onClick={function resetaCNH2() {
              setCnh2('');
            }}
            aria-label="delete"
          >
            <DeleteIcon />
          </IconButton>
        </div>
        <div>
          <TextField
            id="cpf"
            value={cpf}
            onChange={(e) => setCpf(e.target.value)}
            label="CPF Frente"
            type="file"
            variant="outlined"
            inputProps={{ accept: '.png, .pdf, .jpg, .jpeg' }}
            InputLabelProps={{
              shrink: true,
            }}
          ></TextField>
          <IconButton
            onClick={function resetaCPF() {
              setCpf('');
            }}
            aria-label="delete"
          >
            <DeleteIcon />
          </IconButton>
        </div>
        <div>

Laravel:

 public function store(Request $request)
  {
    
  $request->file('cnh')->storeAs($request->id_cliente.$request->id_funcionario.'cnhfrente', $request->cnh->getClientOriginalName(), 'gcs');
   
    $data = $request->all();
    return $this->service->store($data);
  }

When I do this, in the cloud, the file I get is a null image configured with the extension of the image I sent in the input.

Does anyone have any idea how I can fix this?

1 Answers

the 'TextField' component by Material UI not works with input field type = file, so I change my input to another and add the code onChange={(e) => setCnh(e.target.files[0])}.

Related