Dont work upload images on yii2... write dont have $addImgFile->extension;...
if i write him .png , i see other error
Exception 'Error' with message 'Call to a member function saveAs() on null'
public function actionMultipleImg()
{
$this->enableCsrfValidation = false;
if (\Yii::$app->request->isPost) {
$post = \Yii::$app->request->post();
$dir = \Yii::getAlias('#productImgPath') . '/additional-image/';
$result_link = str_replace('administrator', '', Url::home(true)) . 'storage/additional-image/';
$addImgFile = UploadedFile::getInstanceByName('ProductImage[attachment]');
$modelProductImage = new ProductImage();
$modelProductImage->filename = strtotime('now') . '_' . \Yii::$app->getSecurity()->generateRandomString(6) . '.'.$addImgFile->extension;
$modelProductImage->load($post);
$modelProductImage->validate();
if ($modelProductImage->hasErrors()) {
$result = ['error' => $modelProductImage->getFirstError('addImgFile')];
} else {
if ($addImgFile->saveAs($dir . $modelProductImage->filename)) {
$imag = \Yii::$app->image->load($dir . $modelProductImage->filename);
$imag->save($dir . $modelProductImage->filename, 90);
$result = ['filelink' => $result_link . $modelProductImage->filename, 'filename' => $modelProductImage->filename];
} else {
$result = ['error' => 'Ошибка'];
}//else
}//else
$modelProductImage->save();
\Yii::$app->response->format = Response::FORMAT_JSON;
return $result;
} else {
throw new BadRequestHttpException('Only POST is allowed');
}
}//action multiple img
my view form where download image
<?php echo FileInput::widget([
'name' => 'ProductImage[attachment]',
'options' => ['accept' => 'image/*','multiple' => true],
'pluginOptions' => [
'deleteUrl' => Url::toRoute(['/product/delete-image']),
'initialPreview' => $model->imagesLinks,
'initialPreviewAsData'=>true,
'overwriteInitial' => false,
'initialPreviewConfig' => $model->imagesLinksData,
'uploadUrl' => Url::to(['/product/multiple-img']),
'uploadExtraData' => [
'ProductImage[product_id]' => $model->id,
],
'maxFileCount' => 10
],
'pluginEvents' => [
'filesorted' => new JsExpression('function(event, params){
$.post("' . Url::toRoute(["/product/sort-image", "id"=>$model->id]) . '", {position:params});
}')
],
]);?>
and its helped
$addImgFile = UploadedFile::getInstanceByName('ProductImage[attachment][0]');
Related
I am trying to manage the mail labels using the gmail api the delete does but when I try to add or modify some it tells me that the arguments are invalid.
My code to modify is the following:
public function editLabelGmail(Request $request)
{
try {
$url = 'https://www.googleapis.com/gmail/v1/users/me/labels';
$token = LaravelGmail::getToken()['access_token'];
$params = [
'id' => $request->id,
'labelListVisibility' => 'labelShow',
'messageListVisibility' => 'show',
'name' => $request->name,
];
$response = Http::asForm()
->put(
$url . '/' . $request->id . '?access_token=' . $token,
$params
)
->json();
return Response($response, 200);
} catch (\Exception $e) {
return Response()->json(
[
'message' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile(),
],
500
);
}
}
And to add:
public function addLabelGmail(Request $request)
{
try {
$url = 'https://gmail.googleapis.com/gmail/v1/users/me/labels';
$token = LaravelGmail::getToken()['access_token'];
$params = [
'labelListVisibility' => 'labelShow',
'messageListVisibility' => 'show',
'name' => $request->name,
'type' => 'user',
];
$response = Http::asForm()
->post($url . '?access_token=' . $token, $params)
->json();
return Response([$response, 'ok'], 200);
} catch (\Exception $e) {
return Response()->json(
[
'message' => $e->getMessage(),
'line' => $e->getLine(),
'file' => $e->getFile(),
],
500
);
}
}
The parameters I am passing from the front end are coming in as follows:
{
"id": "Label_3",
"name": "Test3"
}
Solution:
I was able to solve it by replacing the $response with the following:
Method Add:
$response = Http::post($url . '?access_token=' . $token, $params)->json();
Method Update:
$response = Http::put($url . '?access_token=' . $token, $params)->json();
I want to develop a website using ReactJS as frontend and 2 API projects both develop in Lumen Laravel as backend. I want to post an image from the frontend to API A, and API A will post the image again to API B, API B will process the image using Matlab.
In my cases, when I'm posting the image to API A, the image will not post the image again to API B. But when I change my code, post the image to API B, the image processed by API B. I don't know why API A can't post Image again from frontend to API B.
Here my code.
PostImage.js
postImage(data, token) {
const path = `image`;
const formData = new FormData();
formData.append("file", data.file);
formData.append("matrix", data.matrix);
formData.append("color", data.color);
return axios.post(`${API_A}/${path}`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
token: token,
},
params: {
token: token,
},
})
.catch((error) => {
if (error.response) {
return Promise.reject({
message: error.response.data.error,
code: error.response.status
});
} else if (error.request) {
console.log(error.request);
throw error;
} else {
console.log('Error', error.message);
throw error;
}
});
}
and API A
public function postImage(Request $request)
{
$all_ext = implode(',', $this->image_ext);
$this->validate($request, [
'matrix' => 'integer',
'color' => 'integer',
'file' => 'required|file|mimes:' . $all_ext . '|max:' . $this->max_size,
]);
$model = new UserImage();
$file = $request->file('file');
$store = Storage::put('public/upload', $file);
dd($store);
try {
$response = $this->client->request('POST', 'http://apiB/imageProcess', [
'multipart' => [
[
'name' => 'matrix',
'contents' => (int) $request->get('matrix', 2),
'headers' => [ 'Content-Type' => 'multipart/form-data']
],
[
'name' => 'color',
'contents' => (int) $request->get('color', 1),
'headers' => [ 'Content-Type' => 'multipart/form-data']
],
[
'name' => 'img_file',
'contents' => fopen(storage_path('app/' . $store), 'r'),
'filename' => $file->getClientOriginalName(),
'headers' => [ 'Content-Type' => 'multipart/form-data']
],
]
]);
$image = $response->getBody()->getContents();
$filePath = '/public/' . $this->getUserDir();
$fileName = time().'.jpeg';
if ($result = Storage::put($filePath . '/' . $fileName, $image)) {
$generated = $model::create([
'name' => $fileName,
'file_path' => $filePath,
'type' => 'motif',
'customer_id' => Auth::id()
]);
return response()->json($generated);
}
} catch (RequestException $e) {
echo $e->getRequest() . "\n";
if ($e->hasResponse()) {
echo $e->getResponse() . "\n";
}
return response($e->getResponse());
}
return response()->json(false);
}
API B
public function processImage(Request $request){
$msg = $this->validateParam($request);
if($msg != ''){
return response()->json(array(
'message'=>$msg.' is not valid'
), 200);
}
ini_set('max_execution_time', 1500);
$sourceFolderPath = 'public/img_src/param_temp/before/';
$resultFolderPath = base_path('public\img_src\param_temp\after');
$matrix = $request->input('matrix');
$color = $request->input('color');
$image = $request->file('img_file');
$extension = image_type_to_extension(getimagesize($image)[2]);
$nama_file_save = $sourceFileName.$extension;
$destinationPath = base_path('public\img_src\param_temp\before'); // upload path
$image->move($destinationPath, $nama_file_save);
$sourceFile = $destinationPath .'\\' . $nama_file_save;
$resultFile = $resultFolderPath .'\\'. $resultFileName.'.jpg';
$command = "matlab command";
exec($command, $execResult, $retval);
if($retval == 0){
$destinationPath = base_path('public\img_src\param_temp\after');
$sourceFile = $destinationPath .'\\' . $resultFileName.'.jpg';
$imagedata = file_get_contents($sourceFile);
if(!$imagedata) return $this->errorReturn();
$base64 = base64_encode($imagedata);
$data = base64_decode($base64);
return response($data)->header('Content-Type','image/jpg');
}
return $this->errorReturn();
}
the image saved in API A, but not processed to API B
I don't know where is wrong in my code, but if you have any suggestion, It will be very helpful for me
I am having issues with the following part of my code using graphql-php libraries.
'resolve' =>function($value,$args,$context)
When I run the query:
"http://localhost:8080/index.php?query={certificate(id:"123ecd"){id}}"
I get the below listed message:
{"errors":[{"message":"Internal server error","category":"internal",
"locations":[{"line":1,"column":2}],"path":["certificate"]}],"data":{"certificate":null}}
Secondly when I run a nested query
"http://192.168.211.15:8080/index.php?query{certificates{id,products{id}}}"
I get the below listed response:
{"errors":[{"message":"Internal server error","category":"internal","locations":[{"line":1,"column":26}],"path":["certificates",0,"products"]}
"data":{"certificates":[{"id":"a023gavcx","status":"Valid","products":null}]}}
Below is my complete code:
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
class CertificateType extends ObjectType{
public function __construct(){
$config = [
'name' => 'Certificate',
'fields' => function() {
return [
'id' => [
'type' => Types::nonNull(Types::string()),
],
'number' => [
'type' => Types::int()
],
'first_issue_date' => [
'type' => Types::string()
],
'products' => [
'type' => Types::product(),
'resolve'=> function($value, $args, $context){
$pdo = $context['pdo'];
$cert_id = $value->id;
$result = $pdo->query("select * from products where cert_id = {$cert_id} ");
return $result->fetchObject() ?: null;
}
]
];
}
];
parent::__construct($config);
}
}
use GraphQL\Type\Definition\Type;
class Types extends Type{
protected static $typeInstances = [];
public static function certificate(){
return static::getInstance(CertificateType::class);
}
public static function product(){
return static::getInstance(ProductType::class);
}
protected static function getInstance($class, $arg = null){
if (!isset(static::$typeInstances[$class])) {
$type = new $class($arg);
static::$typeInstances[$class] = $type;
}
return static::$typeInstances[$class];
}
}
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
class ProductType extends ObjectType
{
public function __construct()
{
$config = [
'name' => 'Product',
'fields' => function() {
return [
'id' => [
'type' => Types::nonNull(Types::string()),
],
'primary_activity' => [
'type' => Types::string()
],
'trade_name' => [
'type' => Types::string()
],
];
},
];
parent::__construct($config);
}
}
require_once __DIR__ . '/../../../../autoload.php';
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
define('BASE_URL', 'http://127.0.0.1:8080');
ini_set('display_errors', 0);
$debug = !empty($_GET['debug']);
if ($debug) {
$phpErrors = [];
set_error_handler(function($severity, $message, $file, $line) use (&$phpErrors) {
$phpErrors[] = new ErrorException($message, 0, $severity, $file, $line);
});
}
try {
$dbHost = 'localhost';
$dbName = '*******';
$dbUsername = 'root';
$dbPassword = '*********';
$pdo = new PDO("mysql:host={$dbHost};dbname={$dbName}", $dbUsername, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$appContext = [
'pdo' => $pdo ];
if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
$raw = file_get_contents('php://input') ?: '';
$data = json_decode($raw, true);
} else {
$data = $_REQUEST;
}
$data += ['query' => null, 'variables' => null];
if (null === $data['query']) {
$data['query'] = '{hello}';
}
require __DIR__ . '/types/CertificateType.php';
require __DIR__ . '/types/ProductType.php';
require __DIR__ . '/types/OrganizationType.php';
require __DIR__ . '/Types.php';
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'hello' => [
'description' => ' Hello world',
'type' => Types::string(),
'resolve' => function() {
return 'Hello World';
}
],
'certificate' => [
'type' => Types::listOf(Types::certificate()),
'description' => 'This is the certificate identification',
'args' => [
'id' => Types::string()],
'resolve' => function ($rootValue,$args,$context) {
$pdo = $context['pdo'];
$id = $args['id'];
return $pdo->query("SELECT * from certificates where id ={$id}");
return $data->fetchObject() ?: null;
}
],
'certificates' => [
'type' => Types::listOf(Types::certificate()),
'resolve' => function($rootValue, $args, $context) {
$pdo = $context['pdo'];
$result = $pdo->query("select * from certificates order by id limit 10");
return $result->fetchAll(PDO::FETCH_OBJ);
}
],
]
]);
$schema = new Schema([
'query' => $queryType
]);
$result = GraphQL::execute(
$schema,
$data['query'],
null,
$appContext,
(array) $data['variables']
);
if ($debug && !empty($phpErrors)) {
$result['extensions']['phpErrors'] = array_map(
['GraphQL\Error\FormattedError', 'createFromPHPError'],
$phpErrors
);
}
$httpStatus = 200;
} catch (\Exception $error) {
// Handling Exception
// *************************************
$httpStatus = 500;
if (!empty($_GET['debug'])) {
$result['extensions']['exception'] = FormattedError::createFromException($error);
} else {
$result['errors'] = [FormattedError::create('Unexpected Error')];
}
}
header('Content-Type: application/json', true, $httpStatus);
echo json_encode($result);
Can somebody help me resolve these issues. Thanks in advance
I am working on multiple image uploads i got the problem that 1st image is uploading properly and for second image it shows out the file upload error attack
Can you help me to find out the problem
Controller
public function mimageAction()
{
$form = new MultipleImageForm();
$form->get('submit')->setValue('Submit');
$request = $this->getRequest();
if($request->isPost())
{
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('file');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data); die;
$form->setData($data);
if ($form->isValid())
{
$count = count($data['varad']);
// $dataNew=array(
// 'test'=>trim($data['test']),
// 'file'=>trim($data['file']['name']),
// 'image'=>trim($data['image']['name'])
// );
$request = new Request();
$files = $request->getFiles();
for($i=0;$i<$count;$i++)
{
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload/'); // Returns all known internal file information
//$adapter->addFilter('File\Rename', array('target' =>"public/img/upload" . DIRECTORY_SEPARATOR .$data['varad'][$i]['name'] , 'overwrite' => true));
$filter = new \Zend\Filter\File\RenameUpload("public/img/upload/");
$filter->filter($files['varad'][$i]['name']);
$filter->setUseUploadName(true);
$filter->filter($files['varad'][$i]['name']);
if(!$adapter->receive())
{
$messages = $adapter->getMessages();
print_r($messages);
}
else
{
echo "Image Uploaded";
}
}
// $adapter = new \Zend\File\Transfer\Adapter\Http();
// $adapter->setDestination('public/img/upload/'); // Returns all known internal file information
// $adapter->addFilter('File\Rename', array('target' =>"public/img/upload" . DIRECTORY_SEPARATOR .$image2, 'overwrite' => true));
//
// if(!$adapter->receive())
// {
// $messages = $adapter->getMessages();
// print_r($messages);
// }
// else
// {
// echo "Image Uploaded";
// }
}
}
return array('form' => $form);
}
Form
public function __construct($name = null)
{
parent::__construct('stall');
$this->setAttribute("method","post");
$this->setAttribute("enctype","multipart/form-data");
$this->add(array(
'name' => 'varad',
'attributes' => array(
'type' => 'file',
'multiple'=>'multiple',
),
'options' => array(
'label' => 'First Image',
),
'validators' => array(
'Size' => array('max' => 10*1024*1024),
)
));
$this->add(array(
'name' => 'test',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Text Box',
),
));
$this->add(array(
'name' => 'varad',
'attributes' => array(
'type' => 'file',
'multiple'=>'multiple',
),
'options' => array(
'label' => 'Second Image',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'submit',
));
}
Here i also tried by getting different names for images as well as different procedures for images
I think u can't use
$request->getFiles();
for this solution.
Please try to use $adapter->getFileInfo()
It's getting files from const _FILES.
I give my example for u:
$adapter = new Zend_File_Transfer_Adapter_Http();
$newInfoData = [];
$path = $this->getBannerDirByBannerId($banner->getId());
foreach ($adapter->getFileInfo() as $key => $fileInfo) {
if (!$fileInfo['name']) {
continue;
}
if (!$adapter->isValid($key)) {
return $this->getPartialErrorResult($adapter->getErrors(), $key);
}
$fileExtension = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
$newFileName = $key . '.' . $fileExtension;
if (!is_dir($path)) {
#mkdir($path, 0755, true);
}
$adapter->addFilter('Rename', array(
'target' => $path . $newFileName,
'overwrite' => true
));
$isReceive = $adapter->receive($key);
if ($isReceive) {
$newInfoData[$key] = $newFileName;
}
}
if (!empty($newInfoData)) {
$newInfoData['id'] = $banner->getId();
return BannerModel::getInstance()->updateBanner($newInfoData);
} else {
return new Model_Result();
}
i have a mistake uploading some images on "multiple upload". If i try to upload the galeries without these images the widget works correctly.
The Image: http://s27.postimg.org/a6qosyctv/Esta_Imagen_Tira_Error.jpg
My form:
$form = ActiveForm::begin([
'id' => 'Item',
'layout' => 'horizontal',
'enableClientValidation' => false,
'errorSummaryCssClass' => 'error-summary alert alert-error',
'options' => ['enctype'=>'multipart/form-data']
]);
$form->field($gallery, 'images[]')->widget(\kartik\file\FileInput::classname(), [
'options' => [
'multiple' => true,
],
'pluginOptions' => [
'uploadUrl' => 'javascript:;',
'showCaption' => false,
'showUpload' => false,
'overwriteInitial' => false,
'allowedFileExtensions' => ['jpg', 'jpeg', 'png'],
'layoutTemplates' => [
'actionUpload' => '',
],
'browseIcon' => '',
'browseLabel' => Yii::t('app', 'Select Files'),
'browseClass' => 'btn btn-block',
'removeLabel' => Yii::t('app', 'Remove All File'),
'removeClass' => 'btn btn-block',
],
]);
My controller:
public function actionCreate()
{
$model = new Hotel();
$model->setCurrentLanguage();
$model->itemType = IElement::ITEM_TYPE_HOTEL;
if ($model->load($_POST)) {
$model->coverPhoto = UploadedFile::getInstance($model, 'coverPhoto');
if ($model->save()) {
if (isset($_POST['Gallery'])) {
$gallery = new Gallery();
$gallery->setAttributes($_POST['Gallery']);
$gallery->idElement = $model->idItem;
$gallery->itemType = IElement::ITEM_TYPE_HOTEL;
$gallery->images = UploadedFile::getInstances($gallery, 'images');
$gallery->save();
}
return $this->redirect(['index']);
}
}
return $this->render('create', [
'model' => $model,
'gallery' => new Gallery(),
]);
}
Gallery Model:
public $images = [];
public function rules()
{
return array_merge(parent::rules(), [
[['images', 'removedImages'], 'safe']
]);
}
public function save($runValidation = true, $attributeNames = null)
{
$transaction = $this->getDb()->beginTransaction();
if(parent::save($runValidation, $attributeNames)){
foreach($this->images as $image){
/* #var UploadedFile $image */
if(!GalleryItem::generateFromImage($image, $this)){
$transaction->rollBack();
return false;
}
}
if(strlen($this->removedImages) > 0){
foreach(explode(',', $this->removedImages) as $itemId){
$albumItem = GalleryItem::findOne($itemId);
if($albumItem instanceof GalleryItem && !$albumItem->delete()){
$transaction->rollBack();
return false;
}
}
}
$transaction->commit();
return true;
}
$transaction->rollBack();
return false;
}
Gallery Item Model:
public static function generateFromImage($imageFile, $gallery)
{
$image = new self;
$image->idGallery = $gallery->primaryKey;
$image->galleryItemOrder = time();
$path = $image->getBasePath();
if(!file_exists($path)) {
mkdir($path, 0777, true);
}
$name = uniqid().'_'.strtr($imageFile->name, [' '=>'_']);
$imageFile->saveAs($path.DIRECTORY_SEPARATOR.$name);
$image->picture = $name;
// var_dump($image->attributes);die();
if(!$image->save()){
#unlink($path.DIRECTORY_SEPARATOR.$name);
return false;
}
return true;
}