Advertisement
Guest User

Laravel React.js

a guest
Oct 13th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. <?php
  2.  
  3. Route::get('/', function () {
  4. return view('welcome');
  5. });
  6.  
  7. Route::post('/', 'FileuploadController.php@store');
  8. ___________________________________________________________________________________________________________________________
  9. <?php
  10.  
  11. namespace App\Http\Controllers;
  12.  
  13. use Illuminate\Http\Request;
  14.  
  15. class FileuploadController extends Controller {
  16.  
  17. public function store(Request $request) {
  18. if($request->get('file')) {
  19. $image = $request->get('file');
  20. $name = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];
  21. \Image::make($request->get('file'))->save(public_path('images/').$name);
  22. }
  23.  
  24. $fileupload = new Fileupload();
  25. $fileupload->filename=$name;
  26. $fileupload->save();
  27.  
  28. return response()->json('Successfully added');
  29. }
  30. }
  31. __________________________________________________________________________________________________________________________
  32. import React, { Component } from 'react';
  33. import axios from 'axios';
  34.  
  35. export default class FileUploadComponent extends Component
  36. {
  37. constructor(props) {
  38. super(props);
  39. this.state ={
  40. image: ''
  41. };
  42. this.onFormSubmit = this.onFormSubmit.bind(this)
  43. this.onChange = this.onChange.bind(this)
  44. this.fileUpload = this.fileUpload.bind(this)
  45. }
  46.  
  47. onFormSubmit(e){
  48. e.preventDefault();
  49. this.fileUpload(this.state.image);
  50. }
  51.  
  52. onChange(e) {
  53. let files = e.target.files || e.dataTransfer.files;
  54. if (!files.length)
  55. return;
  56. this.createImage(files[0]);
  57. }
  58.  
  59. createImage(file) {
  60. let reader = new FileReader();
  61. reader.onload = (e) => {
  62. this.setState({
  63. image: e.target.result
  64. })
  65. };
  66. reader.readAsDataURL(file);
  67. }
  68.  
  69. fileUpload() {
  70. const url = '/';
  71. axios.post(url).then(response => {
  72. console.log(response);
  73.  
  74. this.setState({
  75. file: this.state.image
  76. });
  77. });
  78. }
  79.  
  80. render() {
  81. return(
  82. <form onSubmit={this.onFormSubmit}>
  83. <h1>React js Laravel File Upload Tutorial</h1>
  84. <input type="file" onChange={this.onChange} />
  85. <button type="submit">Upload</button>
  86. </form>
  87. )
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement