Skip to content

Instantly share code, notes, and snippets.

@Bryan-Herrera-DEV
Created April 11, 2022 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bryan-Herrera-DEV/e16e04f973f9ae5f81adde307939176a to your computer and use it in GitHub Desktop.
Save Bryan-Herrera-DEV/e16e04f973f9ae5f81adde307939176a to your computer and use it in GitHub Desktop.
Cómo subir archivos en varias partes usando FormData con React Hook Form

Cómo subir archivos en varias partes usando FormData con React Hook Form

Crear un servidor Express

npm i express
npm i cors express-fileupload

Respuesta a una llamada POST a un endpoint que hemos especificado.

import React from "react";
import { usoForm } from "react-hook-form";
function App(){
	const { register, handleSubmit } = userForm();
	const onSubmit = () => {};
	return (
		<div className="App">
			<form onSubmit={handleSubmit(onSubmit )}>
				<input type="file" {...register("file")} />
				<input type="submit"/>
			</form>
		</div>
	);
}
export default App;

Crear un proyecto React

npx crate-react-app react-hook-form-multipart-upload

Después de que tu proyecto esté listo, vamos a ir al directorio de nuestro proyecto e instalar el paquete React Hook Form.

cd react-hook-form-multipart-upload
npm install react-hook-form

npm run start

Carga de archivos multiparte con el formulario React Hook

import React from "react";
import { usoForm } from "react-hook-form";
function App(){
	const { register, handleSubmit } = userForm();
	const onSubmit = () => {};
	return (
		<div className="App">
			<form onSubmit={handleSubmit(onSubmit )}>
				<input type="file" {...register("file")} />
				<input type="submit"/>
			</form>
		</div>
	);
}
export default App;

Refine Create Post Page:

import { useState } from "react";
import { useForm } from "@pankod/refine-react-form";
import { useSelect, useApiUrl } from "@pankod/refine-core";
import axios form "axios";

export const PostCreate: React.Fc = () => {
	const [isUpLoading, setIsUpLoading] = useState<boolean>(false);

	const {
		refineCore: { onFinish, formLoading },
		register,
		handleSubmit,
		formState: { errors },
		setValue
	} = useForm();
	const apiURL = setApiUrl();
	const { options } = useSelect({
		resource: "categories",
	});
	const onSubmitFile = async () => {
		setIsUploading(true);
	const inputFile = document.getElemenById(
			"fileInput",
		) as HTMLInput;
	const formData = new FormData();
	formData.append("file", inputFile?.files?.item(0) as File);
	const res = await axios.post<{ url: string }>(
		`${apiURL}/media/upload`,
		formData,
		{
			withCredentials: false,
			headers: {
					"Access-Control-Allow-Origin": "*",
				},
			} 
		);
	setValue("thumbnail", res.data.url);
	setIsUploading(false);
	};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment