Upload file from VueJS app to API in Laravel - php

I'm trying to upload a file (Excel sheet) from a front-end app build with VueJS to an API build with Laravel 5.5. I've some form request validation which says to me that The file field is required. So the file doesn't get uploaded to my API at all.
VueJS file upload:
onFileChange(e) {
let files = e.target.files || e.dataTransfer.files;
if (files.length <= 0) {
return;
}
this.upload(files[0]);
},
upload(file) {
this.form.file = file;
this.form.put('courses/import')
.then((response) => {
alert('Your upload has been started. This can take some time.');
})
.catch((response) => {
alert('Something went wrong with your upload.');
});
}
this.form is a Form class copied from this project but the data() method returns a FormData object instead of a object.
data() method:
data() {
let data = new FormData();
for (let property in this.originalData) {
data.append(property, this[property]);
}
return data;
}
The route:
FormRequest rules:
public function rules()
{
return [
'file' => 'required',
];
}
If I look to the Network tab in Chrome DevTools it does seem that the request is send correctly: (image after click).
I've tried a lot of things, like sending the excel as base64 to the api. But then I couldn't decode it correctly. So now I'm trying this, but I can't solve the problem.
Edit (controller function)
public function update(ImportRequest $request, CoursesImport $file)
{
$courses = $file->handleImport();
dispatch(new StartCourseUploading($courses, currentUser()));
$file->delete();
return ok();
}

You are getting 422 as status, I hope you aware of this meaning as validation failed according to your Responses class's rule.
In laravel, PUT method won't accept file uploads, so you need to change from PUT to POST.
this.form.post('courses/import')
.then((response) => {
alert('Your upload has been started. This can take some time.');
})
.catch((response) => {
alert('Something went wrong with your upload.');
});
Don't forget to update your routes of laravel.
Other considerations:
Make sure you added property kind of following code
data: {
form: new Form({
file:null
})
},
Check browser request weather sending form data properly or not , I added sample screen shot
My code samples
class Errors {
/**
* Create a new Errors instance.
*/
constructor() {
this.errors = {};
}
/**
* Determine if an errors exists for the given field.
*
* #param {string} field
*/
has(field) {
return this.errors.hasOwnProperty(field);
}
/**
* Determine if we have any errors.
*/
any() {
return Object.keys(this.errors).length > 0;
}
/**
* Retrieve the error message for a field.
*
* #param {string} field
*/
get(field) {
if (this.errors[field]) {
return this.errors[field][0];
}
}
/**
* Record the new errors.
*
* #param {object} errors
*/
record(errors) {
this.errors = errors;
}
/**
* Clear one or all error fields.
*
* #param {string|null} field
*/
clear(field) {
if (field) {
delete this.errors[field];
return;
}
this.errors = {};
}
}
class Form {
/**
* Create a new Form instance.
*
* #param {object} data
*/
constructor(data) {
this.originalData = data;
for (let field in data) {
this[field] = data[field];
}
this.errors = new Errors();
}
/**
* Fetch all relevant data for the form.
*/
data() {
let data = new FormData();
for (let property in this.originalData) {
data.append(property, this[property]);
}
return data;
}
/**
* Reset the form fields.
*/
reset() {
for (let field in this.originalData) {
this[field] = '';
}
this.errors.clear();
}
/**
* Send a POST request to the given URL.
* .
* #param {string} url
*/
post(url) {
return this.submit('post', url);
}
/**
* Send a PUT request to the given URL.
* .
* #param {string} url
*/
put(url) {
return this.submit('put', url);
}
/**
* Send a PATCH request to the given URL.
* .
* #param {string} url
*/
patch(url) {
return this.submit('patch', url);
}
/**
* Send a DELETE request to the given URL.
* .
* #param {string} url
*/
delete(url) {
return this.submit('delete', url);
}
/**
* Submit the form.
*
* #param {string} requestType
* #param {string} url
*/
submit(requestType, url) {
return new Promise((resolve, reject) => {
axios[requestType](url, this.data())
.then(response => {
this.onSuccess(response.data);
resolve(response.data);
})
.catch(error => {
this.onFail(error.response.data);
reject(error.response.data);
});
});
}
/**
* Handle a successful form submission.
*
* #param {object} data
*/
onSuccess(data) {
alert(data.message); // temporary
this.reset();
}
/**
* Handle a failed form submission.
*
* #param {object} errors
*/
onFail(errors) {
this.errors.record(errors);
}
}
var app = new Vue({
el: '#app',
data: {
form: new Form({
file: ''
})
},
methods: {
onSubmit() {
this.form.post('/projects')
.then(response => alert('Wahoo!'));
},
onFileChange(e) {
let files = e.target.files || e.dataTransfer.files;
if (files.length <= 0) {
return;
}
this.upload(files[0]);
},
upload(file) {
this.form.file = file;
this.form.post('courses/import')
.then((response) => {
alert('Your upload has been started. This can take some time.');
})
.catch((response) => {
alert('Something went wrong with your upload.');
});
}
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.2.3/css/bulma.css">
<style>
body {
padding-top: 40px;
}
</style>
</head>
<body>
<div id="app" class="container">
<form method="POST" action="/projects" #submit.prevent="onSubmit" #keydown="form.errors.clear($event.target.name)">
<input type="file" name="image" #change="onFileChange">
<div class="control">
<button class="button is-primary" :disabled="form.errors.any()">Create</button>
</div>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.15.3/axios.js"></script>
<script src="https://unpkg.com/vue#2.1.6/dist/vue.js"></script>
</body>
</html>
Related Links
https://github.com/laravel/framework/issues/17560

If you store your data in an associative array like data:
var formData = new FormData();
Object.keys(data).forEach(function(key, index){
if(Array.isArray(data[key])){
formData.append(key + '[]', data[key]);
} else {
formData.append(key, data[key]);
}
});
formData.append('file', document.getElementById('file_id').files[0]);
axios.post('path', formData).then( res => {
console.log(res);
}).catch(res => {
console.log(res);
});

Related

Symfony 4 - How to valid my token in controller?

in a function of my controller, I initialize a form that I pass in parameter to a view. The form must then redirect to another action of my controller, like this:
Controller : index()
/**
* #Route("/validation/absences", name="validation_index")
*/
public function index(PaginatorInterface $paginator, Request $request, AbsenceService $absenceService)
{
$refusAbsence = new Absence();
$formRefus = $this->createForm(RefusAbsenceType::class, $refusAbsence);
$formRefus->handleRequest($request);
return $this->render('validation/index.html.twig', [
"formRefus" => $formRefus->createView(),
]);
My form action goes to this function :
/**
* Refuser une demande d'absence
*
* #Route("validation/absences/refuser/{id}", name="validation_refuser")
*
* #param Absence $absence
* #return void
*/
public function refuser(Request $request, Absence $absence)
{
$token = $request->get('refus_absence')['_token'];
if (!$this->isCsrfTokenValid('refus_absence__token', $token)) {
throw new \Symfony\Component\Security\Core\Exception\AccessDeniedException('Accès interdit');
}
$commentaire = $request->get('refus_absence')['commentaire'];
dd($commentaire);
}
I get my token back with the request, but I can not get it to be validated. I still have the mistake.
Yet on Symfony's documentation, they say:
if ($this->isCsrfTokenValid('token_id', $submittedToken)) {
// ... do something, like deleting an object
}
And in my HTML, I've :
<input type="hidden" id="refus_absence__token" name="refus_absence[_token]" value="7bbockF5tz3r7Ne9f6dQB7Y5YMcwd1QRES4vHrhQEQE">
in your receiving function, just recreate the form:
$form = $this->createForm(RefusAbsenceType::class, new Absence());
$form->handleRequest($request);
// also checks csrf, it is enabled globally, otherwise, recreate parameters
// in the createForm call.
if($form->isSubmitted() && $form->isValid()) {
$absence = $form->getData();
// do whatever ... persist and stuff ...
}

Laravel AuthController not working when ajax request pass

I am adapting the out-of-the-box AuthController in Laravel 5.2 to suit my needs. I want to implement login form using AJAX. For that I write the code. But when I click on login button then show 302 error and redirect. I don't know what is my mistake.
My JS
function do_login()
{
frm_name = 'userlogin';
username = $('#userlogin input[id=email]').val();
password = $('#userlogin input[id=password]').val();
_token = $('#userlogin input[id=_token]').val();
if(username == '' || password == '') {
$('#flashMessage').attr('class','alert alert-danger');
$('#flashMessage').html('Please specify Username and Password');
} else {
var param = 'username='+ username+ '&password='+ password +'&_token='+ _token;
$.ajax({
type : "POST",
datatype : "json",
url: "auth/login",
data : param,
success : function(data) {
data = JSON.parse(data);
if (data.status == 0) {
$('#myModallogin').modal('hide');
window.location.href = data.redirect_url;
}
if (data.status == 1) {
$('#flashMessage').attr('class','alert alert-danger');
$('#flashMessage').html(data.message);
} else {
onError(data.Error,'#'+ frm_name);
}
}
});
}
}
$(document).ready(function(){
$('#member_login').click(function() {
do_login();
});
});
My route
Route::auth();
Route::post('auth/login', 'Auth\AuthController#userLogin');
My AuthController
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
//protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
public function userLogin() {
$post_data = Request::all();
pr($post_data);exit;
}
}
My route is working properly because when I debug the routes for example Route::post('auth/login', function(){ echo 'aaaaaaaaaa'; }); so it display the aaaaaa. But when I called the function then show 302 error and redirect the page. I don't know what is my mistake. Please suggest me.

Yii2 and OAuth2 Plugin Filsh/yii2-oauth2-server: Unauthorized when sending POST data

EDIT: SOLVED
Apparently this plugin, was having some problem missing the request headers. The solution was adding
SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
To the .htaccess file to make Authorizaion variable available as this issue report says:
https://github.com/yiisoft/yii2/issues/6631
I'm currently working with Yii2 and using this OAuth2 plugin (Filsh/yii2-oauth2-server) for login and to work with tokens from a mobile HTML5 app.
I've configured everything, and it's retrieving the token, but when I try to send the token via POST it throws an error.
I start by calling send() to retrieve the token.
function send(){
var url = "http://www.server.org/app/api/oauth2/rest/token";
var data = {
'grant_type':'password',
'username':'user',
'password':'pass',
'client_id':'clientid',
'client_secret':'clientsecret',
};
$.ajax({
type: "POST",
url: url,
data: data,
success:function(data){
console.log(data);
token = data.access_token;
},
})
};
Then when I perform this a call to createuser().
function createuser(){
var url = "http://www.server.org/app/api/v1/users/create";
var data = {
'callback':'asdf',
'username': 'user',
'password':'pass',
'first_name':'name',
'last_name':'lastname'
};
$.ajax({
type: "POST",
url: url,
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
},
success:function(r){
console.log(r);
},
});
}
It returns
Unauthorized: You are requesting with an invalid credential
When I change to GET instead, it works fine.
This is my controller, I'm already using:
['class' => HttpBearerAuth::className()],
['class' => QueryParamAuth::className(), 'tokenParam' => 'accessToken'],
As authentication method.
<?php
namespace app\api\modules\v1\controllers;
use Yii;
use app\models\OauthUsers;
use yii\rest\ActiveController;
use yii\web\Response;
use yii\helpers\ArrayHelper;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\auth\QueryParamAuth;
use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter;
use filsh\yii2\oauth2server\filters\auth\CompositeAuth;
class UsersController extends \yii\web\Controller
{
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(), [
'authenticator' => [
'class' => CompositeAuth::className(),
'authMethods' => [
['class' => HttpBearerAuth::className()],
['class' => QueryParamAuth::className(), 'tokenParam' => 'accessToken'],
]
],
'exceptionFilter' => [
'class' => ErrorToExceptionFilter::className()
],
'class' => \yii\filters\ContentNegotiator::className(),
]);
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new OauthUsers;
try {
if ($model->load($_POST) && $model->save()) {
return $this->redirect(Url::previous());
} elseif (!\Yii::$app->request->isPost) {
$model->load($_GET);
}
} catch (\Exception $e) {
$msg = (isset($e->errorInfo[2]))?$e->errorInfo[2]:$e->getMessage();
$model->addError('_exception', $msg);
}
return "true";
}
}
This is my configuration object
'oauth2' => [
'class' => 'filsh\yii2\oauth2server\Module',
'tokenParamName' => 'accessToken',
'tokenAccessLifetime' => 3600 * 24,
'storageMap' => [
'user_credentials' => 'app\models\OauthUsers',
],
'grantTypes' => [
'user_credentials' => [
'class' => 'OAuth2\GrantType\UserCredentials',
],
'refresh_token' => [
'class' => 'OAuth2\GrantType\RefreshToken',
'always_issue_new_refresh_token' => true
]
]
]
This is class OauthUsers
<?php
namespace app\models;
use Yii;
use \app\models\base\OauthUsers as BaseOauthUsers;
/**
* This is the model class for table "oauth_users".
*/
class OauthUsers extends BaseOauthUsers
implements \yii\web\IdentityInterface,\OAuth2\Storage\UserCredentialsInterface
{
/**
* #inheritdoc
*/
public static function findIdentity($id) {
$dbUser = OauthUsers::find()
->where([
"id" => $id
])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $userType = null) {
$at = OauthAccessTokens::find()
->where(["access_token" => $token])
->one();
$dbUser = OauthUsers::find()
->where(["id" => $at->user_id])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* Implemented for Oauth2 Interface
*/
public function checkUserCredentials($username, $password)
{
$user = static::findByUsername($username);
if (empty($user)) {
return false;
}
return $user->validatePassword($password);
}
/**
* Implemented for Oauth2 Interface
*/
public function getUserDetails($username)
{
$user = static::findByUsername($username);
return ['user_id' => $user->getId()];
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username) {
$dbUser = OauthUsers::find()
->where([
"username" => $username
])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
I've changed createuser too, but still receiving a 401. I'm not sure it is passing through findIdentityByAccessToken (access_token is in a different table than oauth users, thats why I'm querying it first).
Any thoughts?
I don't know the plugin you are using but what I know is that you can use the Yii2 HttpBearerAuth filter when implementing OAuth 2.0 which means using the HTTP Bearer token. And that token is typically passed with the Authorization header of the HTTP request instead of the body request and it usually looks like :
Authorization: Bearer y-9hFW-NhrI1PK7VAXYdYukwWVrNTkQ1
The idea is about saving the token you received from the server somewhere (should be a safe place) and include it in the headers of the requests that requires server authorization (maybe better explained here, here or here) So the JS code you are using to send a POST request should look more like this :
function createuser(){
var url = "http://www.server.org/app/api/v1/users/create";
var data = {
'callback':'cb',
'username': 'user',
'password':'pass',
'first_name':'name',
'last_name':'lastname'
};
$.ajax({
type: "POST",
url: url,
data: data,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
},
success:function(r){
console.log(r);
},
});
}
Also check in the User class (the one defined in your config files and responsible of authenticating a user) check the implementation of the findIdentityByAccessToken() method. it should usually look like this (see Yii docs for more details) :
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['auth_key' => $token]);
}
This is the function that will receive the token and it should return null when authentication should fail (by default findOne() returns null when no record is found) or returns a User instance to register it and make it accessible within Yii::$app->user->identity or Yii::$app->user->id anywhere inside your app so you can implement whatever logic you need inside it like checking the validity of an access token or its existence in a different table.
Apparently this plugin (Filsh/yii2-oauth2-server), was having some problem missing the request headers. The solution was adding
SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0
To the .htaccess file to make Authorizaion variable available as this says:
https://github.com/yiisoft/yii2/issues/6631

Typo3 6.2 eid AjaxDispatcher ignores Controll and action

I’m trying to get my Ajax-Function to call a certain controller inside my Typo3 extension.
After several attempts, I decided to go with the same Ajax-Dispatcher that powermail uses. It does show an output, but it completely ignores the supposed controller and action.
There are two Controllers in my Extension and so far three actions:
Category=>list
Family=>list,compare
PHP:
<?php
namespace Vendor\Myextension\Utility;
use \TYPO3\CMS\Core\Utility\GeneralUtility;
class AjaxDispatcher {
/**
* configuration
*
* #var \array
*/
protected $configuration;
/**
* bootstrap
*
* #var \array
*/
protected $bootstrap;
/**
* Generates the output
*
* #return \string rendered action
*/
public function run() {
return $this->bootstrap->run('', $this->configuration);
}
/**
* Initialize Extbase
*
* #param \array $TYPO3_CONF_VARS The global array. Will be set internally
*/
public function __construct($TYPO3_CONF_VARS) {
$this->configuration = array(
'pluginName' => 'my_plugin',
'vendorName' => 'Vendor',
'extensionName' => 'myextension',
'controller' => 'Family',
'action' => 'compare',
'mvc' => array(
'requestHandlers' => array(
'TYPO3\CMS\Extbase\Mvc\Web\FrontendRequestHandler' => 'TYPO3\CMS\Extbase\Mvc\Web\FrontendRequestHandler'
)
),
'settings' => array()
);
$_POST['request']['action'] = 'compare';
$_POST['request']['controller'] = 'Family';
$this->bootstrap = new \TYPO3\CMS\Extbase\Core\Bootstrap();
$userObj = \TYPO3\CMS\Frontend\Utility\EidUtility::initFeUser();
$pid = (GeneralUtility::_GET('id') ? GeneralUtility::_GET('id') : 1);
$GLOBALS['TSFE'] = GeneralUtility::makeInstance(
'TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController',
$TYPO3_CONF_VARS,
$pid,
0,
TRUE
);
$GLOBALS['TSFE']->connectToDB();
$GLOBALS['TSFE']->fe_user = $userObj;
$GLOBALS['TSFE']->id = $pid;
$GLOBALS['TSFE']->determineId();
$GLOBALS['TSFE']->getCompressedTCarray();
$GLOBALS['TSFE']->initTemplate();
$GLOBALS['TSFE']->getConfigArray();
$GLOBALS['TSFE']->includeTCA();
}
}
$eid = GeneralUtility::makeInstance('Vendor\Myextension\Utility\AjaxDispatcher', $GLOBALS['TYPO3_CONF_VARS']);
echo $eid->run();
Ajax:
var read = 'string';
var requestData = {'value': read};
var currentUrl = window.location;
$.ajax({
url: currentUrl,
type: 'POST',
data: {
eID: "ajaxDispatcherMyextension",
request: {
controller: 'Family',
action: 'compare',
arguments: {
'test': requestData
}
}
},
dataType: 'html',
success: function(success) {
console.log('success ' + success);
$('#test').html(success);
}
});
Instead of showing family->compare the Ajax puts out category->compare. I don’t understand why.
Can someone please help? I'm working on this problem for over 2 days now...
I don't know exactly what you mean. If you want to trigger an AJAX request while clicking on a link you can do the following in the belonging view of your action. In this example the script will output the AJAX response.
1) Create a ViewHelper containing something like that:
$uriBuilder = $this->controllerContext->getUriBuilder();
$uri = $uriBuilder->uriFor(
'title',
array("param1" => $value1, "param2" => $value2),
'<controllerName>',
'<extKey>',
'<pluginName>');
return '<a id="link" href="'.$uri.'">';
2) Call the ViewHelper in your view template and add a output container div with an id.
3) Implement the JavaScript for AJAX call
function loadurl(dest, obj) {
try {
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
console.log(e);
}
xmlhttp.onreadystatechange = function() {
triggered(obj);
};
xmlhttp.open("GET", dest);
xmlhttp.send(null);
}
function triggered(obj) {
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
document.getElementById(obj).innerHTML = xmlhttp.responseText;
}
}
window.addEventListener("load", function() {
var item = document.getElementsById('link');
item.addEventListener('click', function(event) {
event.preventDefault();
var href = this.childNodes[1].getAttribute("href");
loadurl(href, 'idOfOutputContainer');
}
}
It's not implemented in 6.2 as noted in my bug report: action and controller not used in RequestBuilder.php:loadDefaultValues

Zend From file upload not working

I'm having some issues uploading a file using Zend Framework. I have created a form, listed below, and have passed the data input to my model where I am attempting to upload the file. IT seems only to get the file name however and fails to upload to my uploads directory.
Form
<?php
class Application_Form_Admin extends Zend_Form
{
public function init()
{
// Set the method for the display form to POST
$this->setMethod('post');
// set the data format
$this->setAttrib('enctype', 'multipart/form-data');
// Add the title
$this->addElement('file', 'ogimage', array(
'label' => 'Default App Image',
'required' => false
));
// Add the submit button
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Submit',
));
// And finally add some CSRF protection
$this->addElement('hash', 'csrf', array(
'ignore' => true,
));
}
}
Controller
<?php
class AdminController extends Zend_Controller_Action
{
/**
* #var The Admin Model
*
*
*/
protected $app = null;
/**
* init function.
*
* #access public
* #return void
*
*
*/
public function init()
{
// get the model
$this->app = new Application_Model_Admin();
}
/**
* indexAction function.
*
* #access public
* #return void
*
*
*/
public function indexAction()
{
// get a form
$request = $this->getRequest();
$form = new Application_Form_Admin();
// pre populate form
$form->populate((array) $this->app->configData());
// handle form submissions
if($this->getRequest()->isPost()) {
if($form->isValid($request->getPost())) {
// save the clips
$this->app->saveConfig($form);
// redirect
//$this->_redirect('/admin/clips');
}
}
// add the form to the view
$this->view->form = $form;
}
}
Model
class Application_Model_Admin
{
/**
* #var Bisna\Application\Container\DoctrineContainer
*/
protected $doctrine;
/**
* #var Doctrine\ORM\EntityManager
*/
protected $entityManager;
/**
* #var ZC\Entity\Repository\FacebookConfig
*/
protected $facebookConfig;
/**
* Constructor
*/
public function __construct(){
// get doctrine and the entity manager
$this->doctrine = Zend_Registry::get('doctrine');
$this->entityManager = $this->doctrine->getEntityManager();
// include the repository to get data
$this->facebookConfig = $this->entityManager->getRepository('\ZC\Entity\FacebookConfig');
}
/**
* saveConfig function.
*
* #access public
* #param mixed $form
* #return void
*/
public function saveConfig($form){
// get the entity
$config = new \ZC\Entity\FacebookConfig();
// get the values
$values = $form->getValues();
// upload the file
$upload = new Zend_File_Transfer_Adapter_Http();
$upload->setDestination(APPLICATION_PATH . '/../uploads/');
try {
// upload received file(s)
$upload->receive();
} catch (Zend_File_Transfer_Exception $e) {
$e->getMessage();
}
// get some data about the file
$name = $upload->getFileName($values['ogimage']);
$upload->setOptions(array('useByteString' => false));
//$size = $upload->getFileSize($values['ogimage']);
//$mimeType = $upload->getMimeType($values['ogimage']);
print_r('<pre>');var_dump($name);print_r('</pre>');
//print_r('<pre>');var_dump($size);print_r('</pre>');
//print_r('<pre>');var_dump($mimeType);print_r('</pre>');
die;
// following lines are just for being sure that we got data
print "Name of uploaded file: $name
";
print "File Size: $size
";
print "File's Mime Type: $mimeType";
// New Code For Zend Framework :: Rename Uploaded File
$renameFile = 'file-' . uniqid() . '.jpg';
$fullFilePath = APPLICATION_PATH . '/../uploads/' . $renameFile;
// Rename uploaded file using Zend Framework
$filterFileRename = new Zend_Filter_File_Rename(array('target' => $fullFilePath, 'overwrite' => true));
$filterFileRename->filter($name);
// loop through the clips and add to object
foreach($values as $k => $column){
$config->__set($k, $column);
}
// save or update the clips object
if(empty($values['id'])){
$this->entityManager->persist($config);
} else {
$this->entityManager->merge($config);
}
// execute the query
$this->entityManager->flush();
// set the id
$form->getElement('id')->setValue($config->__get('id'));
}
}
The issue was that I was accessing the form data before the upload with the following line:
// get the values
$values = $form->getValues();
This is now placed after the upload in the model and the file data is accessed instead with the following:
$file = $upload->getFileInfo();
You have to move the file to where you want it. Here is a small snippet that I use in my code
if($form->isValid($request->getPost())) {
$uploadedFile = new Zend_File_Transfer_Adapter_Http();
$uploadedFile->setDestination(APPLICATION_PATH.'/../public_uploads/');
if($uploadedFile->receive()) {
//Code to process the file goes here
} else {
$errors = $uploadedFile->getErrors();
}
$this->app->saveConfig($form);
}
Hope this helps you get started.
to make this work you need to set setValueDisabled = true in your form element otherwise as soon as you call $form->getValues() it will upload the file to the system temp folder.
Currently you are calling $form->getValues() before you are even setting the destination so the file goes to the default (system temp).

Categories