babu.desai@icloud.com's avatar

401 unauthorized error when uploading file

Im trying to upload .xls file via drop zone js. and I'm getting 401 unauthorized.

public function uploadFile(Request $request)

{

    $file = $request->file('file');
    $path = $file->getRealPath();
    return $path;

}
    Dropzone.options.myAwesomeDropzone = {
      paramName: "file", // The name that will be used to transfer the file
      maxFilesize: 10, // MB
      parallelUploads: 10,
      acceptedFiles: '.xls',
      sending: function(file, xhr, formData) {
         formData.append("_token", $('[name=_token').val()); 
      },
      init: function() {

          this.on("success", function(file, responseText) {
            alert(responseText);
            this.removeAllFiles();
            
        });
      },
      error: function(file, responseText){
          alert(responseText);
          this.removeAllFiles();
      }
    };
</script>
                
                
                
                
0 likes
11 replies
Qlic's avatar

You are telling the ajax script to fetch the csrf token, but is there a form initiated on that page with a token field in it? If not try something like:

example. formData.append("_token", '{{ csrf_token() }}');
babu.desai@icloud.com's avatar

getting same 401 error

while ago in my other project i remember doing

public function authorize() { return true; }

but I'm not sure where i put that, also I'm using laravel 5.2 and my post route for this drop zone form is under [web] middleware group, if that helps figuring out whats going on

babu.desai@icloud.com's avatar

Routes

<?php

/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function(){
    
    return view('welcome');
});


/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/

Route::group(['middleware' => ['web']], function () {
    //
});

Route::group(['middleware' => 'web'], function () {
    Route::auth();

    Route::get('/home', 'HomeController@index');
    Route::get('/settings', 'HomeController@settings');
    Route::get('/hotel', 'HomeController@getHotel');
    Route::get('/upload', function(){
        return view('upload');
    });
    Route::post('/upload', 'HomeController@uploadFile');
});

Route::get('/temp', function(){
    return view('temp'); 
});

app.blade.php (this is template)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Hotel4Cast</title>

    <!-- Fonts -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700" rel='stylesheet' type='text/css'>

    <!-- Styles -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
    {{-- <link href="{{ elixir('css/app.css') }}" rel="stylesheet"> --}}
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.2.0/min/dropzone.min.css" type="text/css" />

    <style>
        body {
            font-family: 'Lato';
        }

        .fa-btn {
            margin-right: 6px;
        }
    </style>
</head>
<body id="app-layout">
    <nav class="navbar navbar-default">
        <div class="container">
            <div class="navbar-header">

                <!-- Collapsed Hamburger -->
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#spark-navbar-collapse">
                    <span class="sr-only">Toggle Navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>

                <!-- Branding Image -->
                <a class="navbar-brand" href="{{ url('/') }}">
                    Hotel4Cast
                </a>
            </div>

            <div class="collapse navbar-collapse" id="spark-navbar-collapse">
                <!-- Left Side Of Navbar -->
                <ul class="nav navbar-nav">
                    @if(Auth::user())
                        <li><a href="{{ url('/home') }}">Home</a></li>
                    
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                                Menu <span class="caret"></span>
                            </a>

                            <ul class="dropdown-menu" role="menu">
                                <li><a href="/upload"><i class="fa fa-btn fa-upload"></i>Upload File</a></li>
                                <li><a href="#"><i class="fa fa-btn fa-download"></i>Download File</a></li>
                                <li role="separator" class="divider"></li>
                                <li class="dropdown-header">Switch Property</li>
                                    <li><a href="">Hilton Garden Inn, South Padre Island</a></li>
                                    <li><a href="">Hilton Garden Inn, South Padre Island</a></li>
                            </ul>
                        </li>
                    @endif
                </ul>

                <!-- Right Side Of Navbar -->
                <ul class="nav navbar-nav navbar-right">
                    <!-- Authentication Links -->
                   
                    @if (Auth::guest())
                        
                        <li><a href="{{ url('/login') }}">Login</a></li>
                        
                    @else
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
                                {{ Auth::user()->name }} <span class="caret"></span>
                            </a>

                            <ul class="dropdown-menu" role="menu">
                                <li><a href="{{ url('/logout') }}"><i class="fa fa-btn fa-sign-out"></i>Logout</a></li>
                                <li><a href="{{ url('/settings') }}"><i class="fa fa-btn fa-cog"></i>Settings</a></li>
                            </ul>
                        </li>
                    @endif
                </ul>
            </div>
        </div>
    </nav>

    @yield('content')

    <!-- JavaScripts -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    {{-- <script src="{{ elixir('js/app.js') }}"></script> --}}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.2.0/min/dropzone.min.js"></script>
    
    <script>
        Dropzone.options.myAwesomeDropzone = {
          paramName: "file", // The name that will be used to transfer the file
          maxFilesize: 10, // MB
          parallelUploads: 10,
          acceptedFiles: '.xls',
          sending: function(file, xhr, formData) {
              // Pass token. You can use the same method to pass any other values as well such as a id to associate the image with for example.
             formData.append("_token", '{{ csrf_token() }}'); // Laravel expect the token post value to be named _token by default
          },
          init: function() {

              this.on("success", function(file, responseText) {
                alert(responseText);
                this.removeAllFiles();
                
            });
          },
          error: function(file, responseText){
              alert(responseText);
              this.removeAllFiles();
          }
        };
    </script>
    
</body>
</html>

upload.blade.php (partial page with drop zone form)

@extends('layouts.app')

@section('content')

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <form id="my-awesome-dropzone" method="POST" action="/upload" class="dropzone">
                {{ csrf_field() }}
              <div class="dz-message" data-dz-message>
                <h1 class="text-center"><span class="glyphicon glyphicon-cloud-upload" aria-hidden="true"></span></h1>
                <p class="text-center">Drag n Drop file here to upload, or click here to browse file.</p>
              </div>
              <div class="fallback">
                <input name="file" type="file" multiple />
              </div>
            </form>
        </div>
    </div>
</div>
@endsection

HomeController

<?php

namespace App\Http\Controllers;

use AWS;
use App\Excel;
use Storage;
use App\Http\Requests;
use Illuminate\Http\Request;
class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return Response
     */
    public function index()
    {
        return view('home');
    }
    
    public function settings()
    {
        return view('settings');
    }
    
    public function getHotel()
    {
      $s3 = AWS::createClient('s3');
        $s3->putObject(array(
            'Bucket'     => 'hotel4cast',
            'Key'        => 'temp/test',
            'SourceFile' => public_path().'/test.txt',
        ));
        return view('hotel');
    }
    
    public function uploadFile(Request $request)
    {
        $file = $request->file('file');
        
        $path = $file->getRealPath();
        
        return $path;
        
       
        
    }
    
}

Qlic's avatar

What happens when you remove the construct meyhod from your controller?

babu.desai@icloud.com's avatar

it works!!!! without construct, but how do i keep that route behind auth though ?

Qlic's avatar

Well, that's what we will have to find out, it looks like the dropzone post does not have an auth session.

What do you see when you place dd(\Auth::user()); as the first line in your uploadFile method?

babu.desai@icloud.com's avatar

i haven't tried that yet, but i put the get route of /upload under auth middleware and now its working

tptompkins's avatar

What was the fix here? I'm having the same problem with Dropzone + a Spark api call. It works fine if use a standard route that goes through the auth middleware but I get a 401 unauthorized error if I use an api route that goes through the auth:api middleware. Any suggestions on how I can fix this?

Thanks in advance!

Tommy

Please or to participate in this conversation.