Search code examples
laravelimageuploadpublic

Image upload on laravel doesn't work online


I finished my project, when I uploaded it to my online server, they do not allow you to change the root map, so I used .htaccess file to acces directly the public map, but when I submit a form, I cannot open the image after upload, and I cant find it in the directories, here is my controller code

if ($request->hasFile('image')) {
            $filenameWithExt = $request->file('image')->getClientOriginalExtension();
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
            $extension = $request->file('image')->getClientOriginalExtension();
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            $request->file('image')->storeAs('public/images', $fileNameToStore);
        } else {
            $fileNameToStore = 'noimage.jpg';
        }

and this is the Html to upload it

<div class="form-group">
    <label>Upload foto's</label>
       <div class="custom-file">
           <input type="file" name="image" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01" multiple>
           <label class="custom-file-label" for="inputGroupFile01">Selecteer bestanden</label>
     </div>
</div>

And this is my HTML to show it or download it

<tr>
   <th>Foto's</th>
        @if( $retour->images === 'noimage.jpg')
           <td>Geen foto beschikbaar</td>
        @else
           <td><a download="retourmelding_{{$retour->firmaname}}"
               href="/storage/images/{{$retour->images}}" title="Foto">
               <img alt="Foto" src="/storage/images/{{$retour->images}}">
               </a>
           </td>
        @endif
</tr>

And this works locally perfect, but online not, help me please


Solution

  • When you fetching a file like you specified above in href. locally it works because your local machine can render the /storage folder path in href but in live server you need to specify like this:

    {{ URL::to('/') }}/images/stackoverflow.png
    

    Now checkout this solution:

    link your storage folder by following command:

    php artisan storage:link 
    
    

    Access the file from blade file like this:

    
    <td>
    <a download="retourmelding_{{$retour->firmaname}}" href="{{ URL::to('/') }}/public/storage/images/{{$retour->images}}" title="Foto">
    <img alt="Foto" src="{{ URL::to('/') }}/public/storage/images/{{$retour->images}}"></a>
    </td>