本文介绍了如何在 Yii2.0 中通过 POST API 将文件上传到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通过这个链接在 yii2 中制作了一个模型http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html我使用 POST 请求将文件发布到 API 并在我的控制器中获取所有文件信息,但无法使用使用上述链接创建的 Yii2.0 模型上传文件,正常的 PHP 文件上传代码工作正常.这是我的控制器代码
I make a model in yii2 from this linkhttp://www.yiiframework.com/doc-2.0/guide-input-file-upload.htmlI post the file using POST request to API and got all file information in my controller but unable to upload file using this Yii2.0 model created using above link normal PHP file upload code work fine.Here is my controller code
public function actionUploadFile()
{
$upload = new UploadForm();
var_dump($_FILES);
$upload->imageFile = $_FILES['image']['tmp_name'];
//$upload->imageFile = $_FILES;
var_dump($upload->upload());
}
我的模型代码是
class UploadForm extends Model
{
/**
* @var UploadedFile
*/
public $imageFile;
public function rules()
{
return [
[['imageFile'], 'safe'],
[['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
try {
if ($this->validate()) {
$this->imageFile->saveAs('/var/www/html/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
var_dump("Jeree");
return true;
} else {
var_dump($this->getErrors());
return false;
}
}catch (ErrorException $e) {
var_dump($e->getMessage());
}
}
}
推荐答案
试试这个方法
public function actionUpload()
{
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->validate()) {
$model->file->saveAs('/var/www/html/' . $model->file->baseName . '.' . $model->file->extension);
}
}
return $this->render('upload', ['model' => $model]);
}
这篇关于如何在 Yii2.0 中通过 POST API 将文件上传到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!