将文件内容直接导入数据库 – 需要修复的Excel电子表格
我正在一个项目中,我直接在MySQL数据库中存储文件。 代码工作正常,存储和下载文本文件,图片和PDF,但使用Excel表格时,它有一个问题。
如果我存储一个Excel传播(.xlsx)文件,上传工作正常,但是当我下载文件,下载似乎工作正常,但是当我打开电子表格时,我得到以下内容:
We found a problem with some content in 'filename.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbench, click Yes?'
当我按Yes
我会得到以下内容:
Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded.
当这样做,Excel载入正常,一切看起来不错,但为什么我会得到这个错误,为什么需要修复。
我正在使用以下内容存储文件:
private function writeFileToDatabase($fileName, $tmpName, $type, $fileSize, $fileArea, &$error) { $fileName = mysqli_escape_string($this->conn, $fileName); $fileSize = mysqli_escape_string($this->conn, $fileSize); $type = mysqli_escape_string($this->conn, $type); $fileArea = mysqli_escape_string($this->conn, $fileArea); //Open the uploaded file $fh = fopen($tmpName, 'r'); if (!$fh) { $error = "Could not open uploaded file"; return false; } $content = fread($fh, filesize($tmpName)); $content = mysqli_escape_string($this->conn, $content); fclose($fh); //Store the file in the database $query = "INSERT INTO file_store (RecordID, Area, FileName, ContentType, Size, FileContent) " . "VALUES ('$this->recordID', '$fileArea', '$fileName', '$type', '$fileSize', '$content')"; $result = $this->conn->query($query); }
我使用下面的文件下载:
function downloadFile($fileID) { $fileID = mysqli_escape_string($this->conn, $fileID); $query = "SELECT * FROM file_store WHERE id='$fileID'"; $result = $this->conn->query($query); if ($result) { $data = $result->fetch_array(); header("Content-length: " . $data["Size"]); header("Content-type: " . $data["ContentType"]); header("Content-Disposition: attachment; filename=" . $data["FileName"]); echo $data["FileContent"]; } else { echo mysqli_error($this->conn); } }
感谢您的任何帮助,您可以提供。
后
echo $data["FileContent"];
尝试添加这个:
ob_clean(); flush();
如果这仍然不起作用 – 也许尝试捕捉内容types,如果它不是一个文本文件添加另一个标题:
header('Content-Transfer-Encoding: binary');