我們有如下所示想出瞭解決辦法:
我們與多個路由工作:
1. /import GET
2. /import POST
3. /import-map GET
4. /import-map POST
1)呈現了一個視圖用於上傳csv文件的文件輸入。
2)將文件上傳到臨時路徑,以便我們可以使用它。路徑被保存到會話中並被3)用來打開文件。由於我們必須處理許多不同的編碼,因此上傳函數會執行一些令人討厭的解碼/編碼來獲得有效的utf8文件。
/**
* Upload the given file to a temp path
*
* @param Filesystem $filesystem
* @param $filePath
* @return string
*/
public function upload(Filesystem $filesystem, $filePath)
{
$path = str_random(20);
$fullPath = public_path('temp/' . $path . '.csv');
if (! mb_detect_encoding($filesystem->get($filePath), mb_detect_order(), true))
$filesystem->put($filePath, chr(239) . chr(187) . chr(191) . utf8_encode($filesystem->get($filePath)));
$filesystem->move($filePath, $fullPath);
return $path;
}
3)呈現導入映射視圖。該文件使用會話中的值加載。如果沒有找到會話數據,則用戶被重定向到1)。
<th>
<select name="col-name[{{ $i }}]" data-eq="{{ $i }}" class="form-control">
<option value="">Datenbankspalte auswählen</option>
@foreach($tableColumns as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
@endforeach
</select>
</th>
4)以管理導入的護理:
/**
* Import the uploaded file one row at a time
*
* @param $input
* @return bool
* @throws \Exception
*/
public function import(array $input)
{
if (! array_key_exists('campaign_id', $input))
throw new Exception();
$columns = array_filter($input['col-name']);
if (empty($columns))
throw new Exception();
$this->openFile($input['csvPath']);
foreach ($this->readCsv(null, (array_key_exists('headers', $input) ? 1 : 0)) as $row)
{
$address = new $this->address;
foreach ($columns as $key => $value)
{
if ($value == '')
continue;
$address->$value = $row[$key];
}
$address->save();
$address->campaigns()
->attach($input['campaign_id'], ['client_id' => auth()->user()->client_id, 'user_id' => (array_key_exists('user_id', $input) ? $input['user_id'] : 0)]);
}
return true;
}
這是不是太困難,是不是:-)
來源
2015-09-08 07:23:58
Tim
謝謝你的分享!我真的很想看到表單/導入POST頁面以及:) – cevizmx
究竟哪個部分? '/ import POST'沒有頁面,因爲它只上傳文件並重定向到映射部分。 – Tim