如何通过Yii2.0的POST API将文件上传到服务器?
问题描述:
我从这个链接制作yii2的模型 http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html 我使用POST请求将文件发布到API,并获取了我的控制器中的所有文件信息,但无法使用上面链接正常PHP文件上传创建的Yii2.0模型上传文件代码工作正常。 这里是我的控制器代码如何通过Yii2.0的POST API将文件上传到服务器?
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]);
}
显示你的模型和控制器请 – scaisEdge
我改变的问题,如果您有任何方法来克服它,然后让我知道 –
我不是一个专家,但为什么你使用$ _files而不是$ _post ?.和'/ var/wwww/html /'是绝对路径而不是相对路径...和'wwww'4w?是对的? – scaisEdge