1 回答

TA貢獻1820條經(jīng)驗 獲得超10個贊
我花了至少10天的時間在網(wǎng)上廣泛搜索并測試了各種解決方案才解決這個問題。
上述問題的答案是不可能將二進制字符串直接保存到 SQL Server 數(shù)據(jù)庫中。該文件需要作為字符串發(fā)送hex。
解決方案:
public function asBinary($content): ?string
{
$fileName = $this->create($content);
$fileAsBinary = file_get_contents(Yii::$app->cache->cachePath . '/' . $fileName);
return $fileAsBinary;
}
/**
* zips file in cache folder into archive
*/
public function create($content): ?string
{
$zipName = \microtime();
try {
$zip = new \ZipArchive;
if ($zip->open(Yii::$app->cache->cachePath . '/' . $zipName, \ZipArchive::CREATE) === true) {
$zip->addFromString(time().'.RTF', $content);
$zip->close();
} else {
throw new Exception(Yii::t('app', 'Archive could not be created in cache folder.'));
}
} catch (\Throwable $th) {
throw $th;
}
return $zipName ?? null;
}
//return file as Hex string
public function asHex($content): string
{
$fileAsBinary = $this->asBinary($content);
$unpackedBinaryFile = unpack('H*hex', $fileAsBinary);
$fileAsHex = '0x' . $unpackedBinaryFile['hex'];
return $fileAsHex;
}
填充 $model 中的 ZIPFILE
$model->ZIPFILE = (new Zip)->asHex($model->ZIPFILE);
zip 文件需要轉(zhuǎn)換為hex可以直接保存到 SQL Server 中的字符串。VARBINARYSQL Server在插入數(shù)據(jù)庫時會將其轉(zhuǎn)換為。
由于不清楚的原因,我無法使用 Yii2 的準(zhǔn)備好的語句傳遞 ZIPFILE。每次都會出錯。另外,無法使用 ActiveRecord 的$model->save()方法進行保存。必須使用 SQL 查詢字符串插入。如果有人能說出原因,那就太好了。
- 1 回答
- 0 關(guān)注
- 102 瀏覽
添加回答
舉報