在laravel 5.4中使用CSV标头创建表

时间:2017-06-14 16:18:25

标签: laravel

我想在上传文件时使用CSV文件标题创建表格。

如果表不存在,则使用CSV标头创建表 否则只需将数据导入指定的表。

这是我的文件上传代码。

    if($request->hasFile('file'))
    {
    $this->validate($request, ['file' => 'mimes:txt,xls,tsv,xlsx' ]);
        //Get original file name
        $filename = $request->file->getClientOriginalName();

        //Get original file extention
        $fileExtention = $request->file->getClientOriginalExtension();

        //get upload user id
        $uploadedUserId = Auth::user()->id;

        //get file upload timestamp in microseconds
        $microseconds = microtime(true);

        //remove special characters from file name
        $sansSpecial = preg_replace('/[\'\"\,\(\)\s]/', '_',$filename);

        //prepend timestamp to modified file name
        $prependTimestamp = $microseconds.'-'.$sansSpecial;

        //create unique hash code from modified file name
        $uniqueFileHash = Hash::make($prependTimestamp);



        $uploadDirectory ='/app/public';
        $uploadPath = storage_path().$uploadDirectory;

         if(Storage::exists('./public/'.$filename))
        {
            Use the path info helper function to get file info.
            $fileInfo= pathinfo($filename);

            //Add timestamp to file if file already exist.
            $finsert = $fileInfo['filename'].date('(m-d-y h i s)').'.'.$fileExtention;

            //Store file into directory.
            $insert = $request->file->storeAs('./public/',$finsert);

            //New upload object.        
            $file = new Upload;

            //Assign new file name
            $file->file_name = $finsert;

            //Assign new modiefied file name with prepended timestamp
            $file->modified_file_name = $prependTimestamp;

            //Assign unique file hash.
            $file->unique_file_hash = $uniqueFileHash;

            //Assign full file path
            $file->file_full_path = $uploadPath;

            //Assign uploaded user id
            $file->uploaded_user_id = $uploadedUserId;

            //Store all informamation into database.
            $file->save();
        }

0 个答案:

没有答案