Upload PDF file in React, Laravel

Today, I will show How to upload pdf files and docs files in React Js and Laravel. Upload PDF file in React, Laravel.

How to Upload PDF and Doc Files in Laravel API

We can upload any kind of file in Laravel using API. I am using Laravel8 You can use 6, 7, or Laravel8. For the Front-end, You can use any language such as Angular, Vue, or React JS.

See our More Tutorials on React and Laravel

Image Cropping in React JS

How to Highlight a Deleted Row in PHP

Display Selected Row record in Material UI Model Box using React

React dropdown select

– To Install Laravel in Your System Use the below command

composer create-project –prefer-dist laravel/laravel Project_Name

– To Install React in Your System Use the below command

npx create-react-app project_name

– To Install Material UI in React

I am using Material UI for React, You can use Bootstrap for design, To install Material UI in your react project use the below command

// with npm
npm install @material-ui/core

// with yarn
yarn add @material-ui/core

Coding Part Starts Here ( Fornt-End React Part )

I am using a single file in React and the file name is ImageCrop. I will hit this URL for PDF File upload in Laravel http://localhost:8000/api/upload ( This is called an API URL )

src/mageCrop.js

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import MuiDialogTitle from '@material-ui/core/DialogTitle';
import MuiDialogContent from '@material-ui/core/DialogContent';
import MuiDialogActions from '@material-ui/core/DialogActions';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import PublishIcon from '@material-ui/icons/Publish';

import {useState,useEffect,useCallback, useRef} from 'react';

import CloudUploadIcon from '@material-ui/icons/CloudUpload';
import { useHistory } from "react-router-dom";
import Alert from '@material-ui/lab/Alert';
import 'react-image-crop/dist/ReactCrop.css';
import ReactCrop from 'react-image-crop';

import { makeStyles } from "@material-ui/core/styles";


const styless = makeStyles((theme) => ({
  root: {
    background: '#4caf50'
  }
}));

const styles = (theme) => ({
  root: {
    margin: 0,
    padding: theme.spacing(2),
  },
  closeButton: {
    position: 'absolute',
    right: theme.spacing(1),
    top: theme.spacing(1),
    color: theme.palette.grey[500],
  },
});

const DialogTitle = withStyles(styles)((props) => {
  const { children, classes, onClose, ...other } = props;
  return (
    <MuiDialogTitle disableTypography className={classes.root} {...other}>
      <Typography variant="h6">{children}</Typography>
      {onClose ? (
        <IconButton aria-label="close" className={classes.closeButton} onClick={onClose}>
          <CloseIcon />
        </IconButton>
      ) : null}
    </MuiDialogTitle>
  );
});

const DialogContent = withStyles((theme) => ({
  root: {
    padding: theme.spacing(2),
  },
}))(MuiDialogContent);

const DialogActions = withStyles((theme) => ({
  root: {
    margin: 0,
    padding: theme.spacing(1),
  },
}))(MuiDialogActions);

export default function CustomizedDialogs(props) {

  // More Code for Image Crop 
  const [upImg, setUpImg] = useState();
  const imgRef = useRef(null);
  const previewCanvasRef = useRef(null);
  const [crop, setCrop] = useState({ unit: '%', width: 30, aspect: 16 / 9 });
  const [completedCrop, setCompletedCrop] = useState(null);


  const classes = styless();
  

  const onSelectFile = (e) => {


    if (e.target.files && e.target.files.length > 0) {
      const reader = new FileReader();
      reader.addEventListener('load', () => setUpImg(reader.result));
      reader.readAsDataURL(e.target.files[0]);
    }
  };


  const [open, setOpen] = React.useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };
  const handleClose = () => {
    setOpen(false);
  };

  const file = new File(["foo"], "", {
    type: "text/plain",
  });

  const [selectedFile, setSelectedFile] = useState();
	const [isFilePicked, setIsFilePicked] = useState(false);

  const changeHandler = (event) => {
		setSelectedFile(event.target.files[0]);
		//setIsSelected(true);
	};
   

  const [fileList, setFileList] = useState();

  useEffect(() => {
    console.log(fileList);
  });

 

  const history = useHistory();
  const[filename,setFileName]= useState([]);
  const[filesNa,setFilesNa]= useState([]);
  const[modelImg,setModelImg] = useState('');
  const[buttonSubmit,setButtonSubmit] = useState('');
  const[sendDocs,setsendDocs]= useState([]);

  const handleChange = (e) =>
  {
      if(!e.target.files[0].name.match(/.(pdf|docx)$/i))
      { 
          const reader = new FileReader();
          reader.addEventListener('load', () => setFileName(reader.result));
          reader.readAsDataURL(e.target.files[0]);
          setFileName(e.target.files[0].name)
          }
        else
        {
          setFilesNa(handleClicks) // Code for Alert message show below 
          setFilesNa(e.target.files[0].name)
          setsendDocs(e.target.files[0])
         // setButtonSubmit( <Button autoFocus onClick={uploadFile} color="primary"> Upload File </Button>);
        }
  }

  
   // Code for Snackbar 

   const [opens, setOpens] = React.useState(false);

   const handleClicks = () => {
     setOpens(true);
   };
 
   const handleCloses = (event, reason) => {
     if (reason === 'clickaway') {
       return;
     }
 
     setOpens(false);
   };

   // Code for Document Upload 

   const [selectedFiles, setSelectedFiles] = useState();

    const uploadImage = async (e) =>
    {
      const formData = new FormData();
      formData.append("file", filename);
      formData.append("name", "DHEERAJ");
  
      await fetch("http://localhost:8000/api/upload", {
        method: "POST",
        body: formData,
      })
      .then((result)=>{
        alert('Image Upload Successully')
      })
      .catch(()=>{
        alert('Error in the Code');
      });
    }

    // Code for File Upload

    const uploadFile = async (e) =>
    {
      const formData = new FormData();
      formData.append("files", sendDocs);
     
      await fetch("http://localhost:8000/api/upload", {
        method: "POST",
        body: formData,
      })
      .then((result)=>{
         alert('File Upload Successully')
      })
      .catch(()=>{
        alert('Error in the Code');
      });
  }


  return (
    <div>
      <Box mt={4} mb={4}><Typography variant="h6"><b> PDF and Docs File Upload in Database using React and Laravel </b></Typography></Box>
    <Button onClick={handleClickOpen} variant="contained" style={{background:"#292b78",color:"white"}} ><PublishIcon/>AddFile</Button>
      <div>  
      <Dialog onClose={handleClose} aria-labelledby="customized-dialog-title" open={open}>
      <DialogTitle id="customized-dialog-title" onClose={handleClose}>
       <div> {filename != '' ? <Typography><b> Image Upload </b></Typography> : <Typography><b> File Upload </b></Typography> } </div>
      </DialogTitle>
       
          <DialogContent dividers>
            <Box >
            <div className="File" style={{width:"300px"}}>
              <Box align="center" mt={2}>
              {filename != '' ? <p></p> : <CloudUploadIcon color="disabled" fontSiz="large"  style={{width:40, height:40,}}/>  }</Box >
              {filename != '' ? <Typography align="center">Selected Image</Typography> : <Typography align="center">{ filesNa != '' ? <p><Alert>{filesNa}</Alert> </p> : <h4>No File Selected</h4>}</Typography>  }    
            </div>
 
            <div className="Image" style={{marginTop:"10px"}}>
             <form>
              <ReactCrop
                src={filename}
              
                style={{height:"120px",width:"260px",marginLeft:"20px"}}
              />
             </form>
            </div>  
            
            {filename != '' ?
              <Box align="center" mt={2}></Box>
              : 
              <Box align="center">
                 <Button variant="contained" size="small" component="label" style={{marginTop:"10px",backgroundColor:"#292b78",color:"white"}}>
                   Choose File
                 <input  type="file" accept=".png, .jpg, .jpeg, .pdf,.docx"  hidden onChange={handleChange}/>
                 </Button>   
             </Box>
            }
         </Box>
            
        </DialogContent>
      <DialogActions>
       {filename != '' ? 
        <Button autoFocus onClick={uploadImage} color="primary">
          Image Upload
        </Button>
        :
         <Button autoFocus onClick={uploadFile} color="primary">
          Upload File
        </Button>
          }
        {/* {buttonSubmit} */}
        <Button autoFocus onClick={handleClose} color="primary">
         Close
        </Button>
       
      </DialogActions>
    </Dialog>
    </div>
    </div>
  );
}

I have used the Dialog box of material UI . Now call the above file in App.js

App.js

import logo from './logo.svg';
import './App.css';
import ImageCrop from './ImageCrop'

function App() {
  return (
    <div className="App">
      <ImageCrop/>
    </div>
  );
}

export default App;

Laravel Part Starts here ( Backend Part Laravel API )

Now, We will see Laravel API for File Upload . Please Make sure your configuration is perfect in laravel. First Make Proper routing in laravel because We will hit the URL for File Upload. I am using only one URL here http://localhost:8000/api/upload ( React will hit this URL for PDF File Upload in Laravel )

Go To routes folder and Open api.php

routes/api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageGallary;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('upload',[ImageGallary::class,'saveImage']);

Route::get('list',[ImageGallary::class,'dataList']);

Route::get('delete/{id}',[ImageGallary::class,'deleteImg']);

Now Our Route is generated, So I will make a controller for further action. Our Controller name ImageGallary

app/http/controller/ImageGallary.php

<?php

namespace App\Http\Controllers;
use \PDF;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Redirect,Response,File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
class ImageGallary extends Controller
{
 
    function saveImage(Request $request)
    {
      if(!$request->file('files'))
      {
         $base64_image = $request->input('file'); // your base64 encoded     
         @list($type, $file_data) = explode(';', $base64_image);
         @list(, $file_data) = explode(',', $file_data); 
         $imageName = str_random(10).'.'.'png';   
         Storage::disk('public')->put($imageName, base64_decode($file_data));
          return response()->json([
          'message' => 'Image Uploaded Successfully'
         ]);
      }
      else
      {
        $name = $request->file('files');
        $path=$request->file('files')->store('/','public');
        return response()->json([
          'message' => 'File Uploaded Successfully'
         ]);
      }          
    }
    function dataList()
    {
      $res =  DB::table('image_gallary')->get();
      return Response::json($res);
    }
    function deleteImg($id)
    {
      $res = DB::table('image_gallary')->where('id', $id)->delete();
      return Response::json($res);
    }
}

Our Coding part is completed and Start Laravel Server and React Server. By default, Laravel runs on 8000, and React runs on 3000.

To Start Laravel Server -> php artisan serve

To Start React -> npm start

Subscribe to My Programming YouTube Channel Before Downloading the code :

Download the Source Code: PDF File Upload in React Laravel

Comments 2

Leave a Reply

Your email address will not be published. Required fields are marked *