如何从Laravel中的视图上传文件?

时间:2019-01-03 13:24:50

标签: php laravel logistic-regression

我正在尝试在控制器中的Request中捕获CSV文件。我已经在使用Laravel中的文件系统上读过documentation,但似乎返回了NULL

在我的控制器内部:

public function index(Request $request)
    {
        $file = $request->file('dataframe'); # This returns null every time
        if(isset($file)):

            $dataset = new CsvDataset($file, 1);
            $vectorizer = new TokenCountVectorizer(new WordTokenizer());
            $tfIdfTransformer = new TfIdfTransformer();

            $samples = [];
            foreach ($dataset->getSamples() as $sample)
                $samples[] = $sample[0];

            $vectorizer->fit($samples);
            $vectorizer->transform($samples);

            $tfIdfTransformer->fit($samples);
            $tfIdfTransformer->transform($samples);

            $dataset = new ArrayDataset($samples, $dataset->getTargets());
            $randomSplit = new StratifiedRandomSplit($dataset, 0.1);

            $classifier = new SVC(Kernel::RBF, 10000);
            $classifier->train($randomSplit->getTrainSamples(), $randomSplit->getTrainLabels());

            $predictedLabels = $classifier->predict($randomSplit->getTestSamples());

            $viewVar = (object) [
                'labels' => $predictedLabels,
                'score'  => Accuracy::score($randomSplit->getTestLabels(), $predictedLabels)
            ];

            return view('home')->with('prediction', $viewVar);

        endif;

        return view('home');
    }

在我看来:

<p>You can upload your dataframe below.</p>
    <form method='GET'>
        <input type='file' name='dataframe'>
        <button type='submit' name='upload'>Predict</button>
    </form>
@if (isset($prediction))
    <p> Score: {{ $prediction->score }} </p>
@endif

当我var_dump()请求时,我可以看到上传的languages.csv文件。如何在$request变量中访问此文件?

1 个答案:

答案 0 :(得分:2)

如果要提交文档,则必须使用POST并输入enctype:

<form method='POST' enctype="multipart/form-data">
    <input type='file' name='dataframe'>
    <button type='submit' name='upload'>Predict</button>
</form>