我需要上传和下载文件与php/mysql在我自己的小项目。
使用post通过表单上传文件,并按以下方式处理:
<?
$passName1 = $_FILES['passport1']['name'];
$tmpName1 = $_FILES['passport1']['tmp_name'];
$fileSize1 = $_FILES['passport1']['size'];
$fileType1 = $_FILES['passport1']['type'];
$fp1 = fopen($tmpName1, 'r');
$pass_1_content = fread($fp1, filesize($tmpName1));
fclose($fp1);
?>
然后我用这个函数上传它们:
$passport1id = insert_user_file ($db, $passName1, $fileType1, $fileSize1, $pass_1_content);
function insert_user_file ($db, $name, $type, $size, $content) {
try {
echo "<br>start insert file $name";
$insertfile = new PDO("mysql:host=".$db['server'].";dbname=".$db['db'], $db['mysql_login'], $db['mysql_pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
// set the PDO error mode to exception
$insertfile->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt=$insertfile->prepare ("INSERT INTO files (name, size, type, content, created) VALUES (:name, :size, :type, :content, NOW())");
$stmt->bindParam(":name", $name);
$stmt->bindParam(":size", $size);
$stmt->bindParam(":type", $type);
$stmt->bindParam(":content", $content);
$stmt->execute();
$file_id = $insertfile->lastInsertId();
return $file_id;
}
catch(PDOException $e) {
echo 'error: '. $e->getMessage();
return false;
}
}
文件名/内容中存在addslashes()似乎没有任何区别。似乎工作正常,但当我用下面的函数取回文件时,它似乎已损坏:
get_file ($db, $_GET['id']);
function get_file ($db, $fileid){
try {
$get_file = new PDO("mysql:host=".$db['server'].";dbname=".$db['db'], $db['mysql_login'], $db['mysql_pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$get_file->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$file = $get_file->prepare("SELECT * FROM files where fileid=:fileid");
$file->bindParam(":fileid", $fileid);
$file->execute();
$file_data = $file->fetch(PDO::FETCH_ASSOC);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header("Content-length: {$file_data['size']}");
header("Content-type: {$file_data['type']}");
header("Content-Disposition: attachment; filename={$file_data['name']}");
echo $file_data['content'];
exit;
}
catch(PDOException $e) {
//echo 'error: '. $e->getMessage();
return false;
}
}
1条答案
按热度按时间6mzjoqzu1#
我已经解决了这个问题!愚蠢的我,我应该把整个代码放在这里,因为它导致了混乱!
罪魁祸首在第2行ob_start();覆盖了如下警告:
第289行后面有几个空格
?> //some spaces were here
这是一个非常愚蠢的错误。非常感谢@marcb暗示我可能会错过一些警告。以后不要留下空白?>