1

Whenever I upload CSV files after the file uploaded it changed to .txt

the path I echo "$path"; showing the file format saved is .txt not .csv.

Is there any way to store the file with actual .csv or I just made mistake somewhere?

here's my form

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Upload file</title>
</head>
<body>
    <form class="" action="{{URL::to('store')}}" enctype="multipart/form-data" method="post">
        <input type="file" name="csv" value="">
        <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
        <br>
        <button type="submit" name="button">upload file</button>
    </form>
</body>
</html>

and here's the controller

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Storage;


class store extends Controller {

    function index(request $request){
        $path=$request->file('csv')->store('csv');

        echo "$path";

    }

}
?> 

result of uploaded csv

csv/VKgVPMvwcQKqpqHAXZ1s6o1IyIbz5BkgQqjxotPc.txt

Thank you.

1 Answer 1

5

You can replace ->store('csv') with ->storeAs('csv', 'filename.csv') to give the file a specific file name with extension. If you don't do that, Laravel will assume the file extension based on the file contents (which, for csv, is basically text).

You can also use $request->file('csv')->getClientOriginalExtension() to get the file extension of the filename with which the user submitted the file. This extension could be altered on purpose by the user though. $request->file('csv')->extension() will give you the file extension that Laravel would give to the file.

To generate a file name hash like this, use Str::random(40) (this is also used by the system itself). So, as a result, you could use something like:

$file = $request->file('csv');
$path = $file->storeAs('csv', \Str::random(40) . '.' . $file->getClientOriginalExtension());
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir! I'm new with Laravel, so I don't know that laravel can assume file extension and change the extension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.