我一直试图从一个特定的目录下载我上传的文件,像这样。
Yii::app()->request->SendFile($model->statement,
file_get_contents($path.$model->statement)
);
它能识别文件并以正确的名称和格式下载,但我得到的不是一个74KB的文件,而是一个1KB的损坏文件。尝试了其他文件,如.doc、.pdf,还是一样。
我并不完全确定file_get_contents到底是做什么的,因为我是从我找到的一个例子中提取的。
要下载的文件之前是用
<div class="row">
<?php echo $form->labelEx($model, 'statement'); ?>
<?php echo $form->fileField($model, 'statement', array('size' => 36, 'maxlength' => 255)); ?>
<?php echo $form->error($model, 'statement'); ?>
</div>
的_form.php,并调整了控制器中的actionCreate。
public function actionCreate($id)
{
$model=new Witness;
$model->ip_id = $id;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
$path = Yii::app()->basePath . '/modules/iris/statements';
if (!is_dir($path)) {
mkdir($path);
}
if(isset($_POST['Witness']))
{
$model->attributes=$_POST['Witness'];
if (@!empty($_FILES['Witness']['name']['statement'])) {
$model->statement = $_POST['Witness']['statement'];
if ($model->validate(array('statement'))) {
$model->statement = CUploadedFile::getInstance($model, 'statement');
} else {
$model->statement = '';
}
$model->statement->saveAs($path . '/' . time() . '_' . str_replace(' ', '_', strtolower($model->statement)));
//$model->doc_type = $model->statement->getType();
//$model->doc_size = $model->statement->getSize();
}
$model->statement = time() . '_' . str_replace(' ', '_', strtolower($model->statement));
if($model->save())
$this->redirect(array('ip/view','id'=>$model->ip_id));
}
$this->render('create',array(
'model'=>$model,
));
}
上传的文件可以打开,没有问题。知道为什么下载会损坏吗?我是不是要先指定文件的类型大小再下载?
对于一个1kb的文件,听起来像是你的服务器在头文件被设置后出现了一个php错误。
用文本编辑器打开下载的文件并检查内容。
我找到了另一个解决方案,而不是使用SendFile函数。把这个放在视图文件中,生成下载链接。
CHtml::link('Click to download file', array('ip/download&id='.$model->file_id));
其中'ip'是模型名称 这将传递file_id到controller.php中创建的函数actionDownload。
public function downloadFile($fullpath){
if(!empty($fullpath)){
header("Content-type:application/pdf"); //for pdf file
//header('Content-Type:text/plain; charset=ISO-8859-15');
//if you want to read text file using text/plain header
header('Content-Disposition: attachment; filename="'.basename($fullpath).'"');
header('Content-Length: ' . filesize($fullpath));
readfile($fullpath);
Yii::app()->end();
}
}
public function actionDownload($id){
$model=Ip::model()->findByPk($id);
$path = Yii::app()->basePath . 'location of file to be downloaded'.$model->filename;
$this->downloadFile($path);
}
这样就可以完全下载文件了。不要担心内容类型,我已经尝试了所有常见的文件类型(.pdf, .doc, .ppt, .png, .jpg),都能完美地工作。
如果你看一下参数列表中的 sendFile
,你可以看到第三个参数是 mimeType
. 事实上,你并没有提出HTTP头文件的响应,所以我对你的初步建议是尝试明确地指定了 Content-Type
响应头。
Yii::app()->request->sendFile(
"Youfile.pdf",
file_get_contents('path/to/file'),
'application/pdf'
);