gpt4 book ai didi

php - 如何为 Yii2 创建文件上传 REST API Controller

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:49:31 27 4
gpt4 key购买 nike

我正在使用 Ionic 框架开发移动应用程序。下面的Yii2 API代码可以用来上传文件,但是不行。它显示以下错误:

i) Undefined offset: 0.

ii) yii\db\BaseActiveRecord->save()

public function actionNew() {
$model = new Apiprofile();
$userid = $_REQUEST['user_id'];
$photo = $_FILES['photo'];
$model->user_id = $userid;
$model->photo = $photo;
$name = $model->user_id;
$model->file = UploadedFile::getInstance($model, 'photo');

if($model->file) {
$model->file->saveAs('uploads/photos/'.$name.'.'.$model->file->extension);
$model->photo = $name.'.'.$model->file->extension;
$model->save();
}

$name = $model->user_id;

if($model->save()) {
echo json_encode(array('status'=>1,'data'=>$model->attributes),JSON_PRETTY_PRINT);
} else {
echo json_encode(array('status'=>0,'error_code'=>400,'errors'=>$model->errors),JSON_PRETTY_PRINT);
}
}

最佳答案

你好,如果你愿意,我将分享我用于在 Yii2 REST 中处理图像的助手类。

在应用程序的基础文件夹中创建文件夹组件,并在该文件夹内创建两个文件夹助手和对象。

 -->assets
-->componests
----->helpers
----->objects
-->config
-->...

之后在对象文件夹中创建类 FileUpload 并将此代码放入其中。

<?php
namespace app\components\objects;


class FileUpload
{
public $error=[];
public $isSuccess=false;
public $file;
public $ready_path;
public $file_type;
public $file_size;
public $file_extension;
public $file_tmp_name;

public $file_name;
public $save_path;

public function __construct($file,$save_path,$ready_path,$required=false)
{
if(!isset($_FILES[$file])){
if($required){
$this->error=['message'=>$file.' is required'];
}
return $this;
}
$this->save_path=$save_path;
$this->ready_path=$ready_path;
$this->file_type = strtolower($_FILES[$file]['type']);
$this->file_name = $_FILES[$file]['name'];
$this->file_tmp_name=$_FILES[$file]['tmp_name'];
$this->file_size = $_FILES[$file]['size'];
$this->file_extension=pathinfo($this->file_name, PATHINFO_EXTENSION);
}

public function setError($error){
if(empty($this->error)){
$this->error=$error;
}
}

}

然后在 helpers 文件夹中创建类 FileUploadHelper,然后将这段代码放入其中。

<?php
namespace app\components\helpers;
use app\components\objects\FileUpload;
use Yii;

class FileUploadHelper
{

private $allowed_files;
private $file_size;
const IMAGE='image';
const FILE='file';

/** File Upload
* @param string $file_name
* @param string $save_path
* @param string $ready_path
* @param string $type
* @param bool $required

* @return \app\components\objects\FileUpload
*/
public static function fileUpload($file_name,$save_path,$ready_path,$type,$required=false){

$image=new FileUpload($file_name,$save_path,$ready_path,$required);
if($type==self::FILE){
$allowed_files=Yii::$app->params['allowed_files'];
$file_size=Yii::$app->params['file_max_size'];
}else{
$allowed_files=Yii::$app->params['allowed_files'];
$file_size=Yii::$app->params['file_max_size'];
}
$dir = realpath(Yii::$app->basePath);
if(in_array($image->file_type,$allowed_files)
&&$image->file_size<$file_size){
$filename = $file_name.'_'.md5(uniqid(time()).time() . '_' . date('YmdHis')) . '.' . $image->file_extension;
$file = $dir . $image->save_path . $filename;
if(move_uploaded_file($image->file_tmp_name, $file)){
$image->file=$image->ready_path. $filename;
$image->isSuccess=true;
$image->setError(['message'=>'file_upload_success']);
}else{
$image->setError(['message'=>'error_try_again']);
}
}else{
$image->setError(['message'=>'file_should_be_no_more_than_given_size']);
}
return $image;
}


/** Delete File
* @param string $ready_file
*/
public static function deleteImage($ready_file){
$dir = realpath(Yii::$app->basePath);
if (strpos($ready_file, 'default') === false){
if(is_file($dir.'/web/'.$ready_file)){
unlink($dir.'/web/'.$ready_file);
}
}
}
}

这就是所有需要的。下面我给大家举个例子

public function actionEditAvatar($id)
{
$product = Product::findOne($id);
if( $product ){
$old_avatar=$product->avatar;
$image=FileUploadHelper::fileUpload(ProductForm::AVATAR,Yii::$app->params['product_path'],Yii::$app->params['product_ready_path'],FileUploadHelper::IMAGE);
if($image->isSuccess) {
$product->avatar = $image->file;
if($product->save()){
FileUploadHelper::deleteImage($old_avatar);
return $product->avatar;
}

}
return $image->error;
}
throw new NotFoundHttpException;
}

上面的代码来自一个真实的项目。 FileUploadHelper 有两个静态类,分别是“fileUpload”和“deleteImage”。FileUploadHelper 需要 fileUpload('file_name','save_path','ready_path','type')'save_path' 是保存文件的位置。'ready_path' 是准备好的 URL 应该是什么样子的。它们在 Yii::$app->params[];

您可以通过属性 isSuccess 检查图像是否成功。如果您有错误,您可以通过属性错误访问它们。就绪文件可以通过属性文件访问。您可以通过静态函数删除图像 deleteImage('saved_image_url');所有这些都用于上述操作。请看。顺便说一下,这里是我使用的参数。不要忘记在 web/uploads 中创建文件夹,并像在配置文件中一样更改文件夹的名称。

return [
'adminEmail' => 'admin@example.com',

'allowed_images' => [ 'image/jpeg', 'image/gif', 'image/png' ],
'allowed_files' => [ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/msword', 'application/pdf','image/jpeg', 'image/gif', 'image/png'],

'image_max_size' => 2097152,
'file_max_size' => 8388608,

'owner_document_path' => '/web/uploads/owner_document/',
'owner_document_ready_path' => 'uploads/owner_document/',

'product_path' => '/web/uploads/product/',
'product_ready_path' => 'uploads/product/',

'complain_photo_path' => '/web/uploads/complain_photo/',
'complain_photo_ready_path' => 'uploads/complain_photo/',

'owner_path' => '/web/uploads/owner/',
'owner_ready_path' => 'uploads/owner/',


'staff_path' => '/web/uploads/staff/',
'staff_ready_path' => 'uploads/staff/',
];

关于php - 如何为 Yii2 创建文件上传 REST API Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36981572/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com