Using Uppy to upload Files from ReactJs to PHP server( Yii2) - php

I have a Form in ReactJs and I want to submit both data and files to my php API ( Yii2) endpoint. (I do not want to use the raw Input file upload form as I want to have functions like file preview, cropping and most importantly progress bar on file upload)
After doing some research, I came across Uppy which seems to be a great tool to help in this task. I have been going through the docs and other materials for a few days now.
I have written a function to upload files using uppy file uploader following tutorials such as https://uppy.io/docs/react/. My function is very buggy as
I do not even see thumbnails generated from files uploaded, I do not see any information on my DragDrop Component.
I am not able to upload the files to my Yii2 API endpoint. I get the error Reason:
CORS header ‘Access-Control-Allow-Origin’ missing with results such
as: Object { successful: [], failed: (1) […], uploadID:
"cjs3mua0g0001245zctq3nbqa" }
Here is my code for the uppy function
AvatarPicker(currentAvatar ){
const {user} = this.props
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: user.username
})
};
const uppy = Uppy({ autoProceed: true })
.use(Dashboard, { trigger: '#select-files' })
.use(GoogleDrive, { target: Dashboard, serverUrl: apiConstants.API_GENERAL_URL+'changeprofilepic' })
.use(Instagram, { target: Dashboard, serverUrl: apiConstants.API_GENERAL_URL+'changeprofilepic' })
.use(Webcam, { target: Dashboard })
.use(Tus, { endpoint: apiConstants.API_GENERAL_URL+'changeprofilepic?access-token='+user.username, requestOptions })
.on('complete', (result) => {
console.log('Upload result:', result)
})
return (
<div>
<img src={currentAvatar} alt="Current Avatar" />
<DragDrop
uppy={uppy}
locale={{
strings: {
// Text to show on the droppable area.
// `%{browse}` is replaced with a link that opens the system file selection dialog.
dropHereOr: 'Drop here or %{browse}',
// Used as the label for the link that opens the system file selection dialog.
browse: 'browse'
}
}}
/>
</div>
)
And in my component render function, I call the AvatarPicker class as show
{
this.AvatarPicker('./../images/master.png')
}
Any heads up on this issue, propose solutions, fixes or new Ideas to get around my task is highly appreciated.

Related

Calling a PHP method inside a controller with Ajax (Laravel)

I have a Controller in my Laravel project called Clientecontroller, it works perfectly. Inside it, I have a method called listar() who brings me client's information.
public function listar(Cliente $cliente) {
$clientes = DB::table('clientes')
->where('documento_id', 1)
->first();
return $clientes;
}
Sure it has some troubles but my main question is, how I call this listar() function from a view with Angular or Ajax or whatever could work.
I am working in a selling system and I have to bring the client information before selecting anything else. I want to write the ID number from the clients in my view and bring the client information from my controller without reloading. But I am still stuck in the processing reaching the listar() function.
Thank you very much.
in your routes.php file add
Route::post('/cliente', 'Clientecontroller#listar');
And now use your ajax call in order to send data to /cliente the data will be sent through to your listar method in the ClienteController.
$.ajax({
type: "POST",
url: '/cliente',
data: { id: 7 }
}).done(function( msg ) {
alert( msg );
});
This question was answered, for more details head over here
1. The classical HTML approach
Let's say you have a button on your page :
<button id="call-listar">Call !</button>
You could send an HTTP Request to your Laravel application like that :
document.querySelector('#call-listar').addEventListener('click', (e) => {
// Use the fetch() API to send an HTTP Request :
fetch('/the-url-of-listar-controller')
.then(response => response.json())
.then(json => {
// Do what you want to do with the JSON
});
});
📖 You can find a very usefull documentation about the fetch() API here : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
2. Inside an Angular Component
This is an other story here, let's say you have this button in your HTML Template :
<button (click)="callListar()">Call !</button>
Inside your TypeScript, you could use HttpClientModule to send an HTTP Request to your Laravel App :
class MyComponent {
constructor(private http: HttpClient){}
callListar() {
this.http.get('/url-of-listar-controller')
.subscribe(response => {
// Do what you want with the response
});
}
}
WARNING : HttpClientModule needed !
You must import the HttpClientModule inside your AppModule or any other module of your Angular App where you want to use this component :
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [...],
imports: [HttpClientModule]
})

Image upload issue with react-native and PHP(CodeIgniter) as backend

I have an app scenario with react native and CodeIgniter as backend.
I have a code snippet to upload image as picked by react-native-image-picker as below:
let formData = new FormData();
let imageBody = {
uri: newImage,
name: 'profilepicture.jpg',
type: 'image/jpeg',
};
formData.append('file', (imageBody)) // case 1 gives network error
formData.append('file', JSON.stringify(imageBody)) //case 2 goes OK
apiUpdateUser(formData)
.then(res => {
this.setState({ showSnack: true, snackText: 'Profile Picture Updated'})
})
.catch(err => {
this.setState({ showSnack: true, snackText: 'Update Failed' })
});
The apiUpdateUser method goes as :
export const apiUpdateUser = body => {
return new Promise((resolve, reject) => {
axios
.post(ApiRoutes.updateUser, body, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(Constant.network.networkError);
});
});
};
The Php code at the backend to handle this upload as usual is:
$file=$this->request->getFile('file');//in CI
$file=$_FILES['file'];//in normal php
My issue is that I do not get anything whatsoever in the $file variabe with either of the methods, The file variable is empty in both the cases.
I've checked the implementation in react native and it doesnt seem to be buggy at all comparing with tutorials/demonstrations online. Also the way of handling at the backend is obvious and Ok.
I'm able to achieve this upload with POSTMAN easily but with react-native I'm facing this error. Can anyone show me some light here??
I am using VUE and sending files using Axios. So I think this may help you out.
I am using the following way of form data to set the files or images.
formData.append('file', this.form.image_url, this.form.image_url.name);
Here this.form.image_url directly refers to the $event.target.files[0]; where $event targets the input.
In the backend, it is the same as you have it here.
This works out well for me. I am unsure of what you are passing as imageBody so it's hard to comment on that.
You can try this
let imageBody = {
uri: newImage,
name: 'profilepicture.jpg',
type: 'image/jpeg',
};
apiUpdateUser(imageBody)
.then(res => {
this.setState({ showSnack: true, snackText: 'Profile Picture Updated'})
})
.catch(err => {
this.setState({ showSnack: true, snackText: 'Update Failed' })
});
export const apiUpdateUser = body => {
return new Promise((resolve, reject) => {
axios
.post(ApiRoutes.updateUser, body, {
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(Constant.network.networkError);
});
});
};
Turns out that the JSON.stringify() was the culprit line.
Without that line, the app was giving out network error.
That's why I had randomly added it just to see if that was the cause of error.
Since, the network error issue was solved with that addition, I didn't give a second thought about it and only thought it to be a file upload issue. Actually, I now see that this is a known issue of a react native flipper version that I have been using which I managed to solve.

Display image url use AXIOS combine with laravel

now im doing AXIOS code combine with laravel to get image from instagram URL. the URL is this https://www.instagram.com/p/B_zZCRpB895/media/?size=t
AXIOS is new from me. to get the image, i tried this simple code. i set this code into my frontend site
<img id="imgsrc" src="" >
<script>
axios
.get('https://www.instagram.com/p/B_zZCRpB895/media/?size=t', {
responseType: 'arraybuffer'
})
.then(response => {
const buffer = Buffer.from(response.data, 'base64');
document.getElementById("imgsrc").src = Buffer;
console.log(Buffer);
})
.catch(ex => {
console.error(ex);
});
</script>
but the image not display into <img id="imgsrc" src="" >
i really want that, when we open the page. the instagram image can display.
how to solve this matter. please help.
you can use file reader to get base64 and set it as the image source :
<script>
axios.get('https://www.instagram.com/p/B_zZCRpB895/media/?size=t', {responseType: "blob"})
.then(function (response) {
var reader = new window.FileReader();
reader.readAsDataURL(response.data);
reader.onload = function () {
document.getElementById("imgsrc").src = reader.result;
}
});
</script>
Is there a particular reason you are retrieving this via an AJAX call using axios?
The endpoint you provided returns an image source already. To make it appear in the image element all you need to do is set the src to the endpoint URL as shown below. Unless you need to run a process to do something to the image you don't need to get the data as an array buffer.
document.getElementById("imgsrc").src = "https://www.instagram.com/p/B_zZCRpB895/media/?size=t";

How to upload the files using VueJS and Laravel 5.3

I am developing SPA using VueJS, Laravel 5.3 and Passport Authentication module.
My Code upto now. and I can get file name selected. Working fine but how to send selected files to make post request to upload the files to the server?
<script>
import {mapState} from 'vuex'
export default{
computed: {
...mapState({
userStore: state => state.userStore
})
},
data () {
return {
fax: {
files: '',
image: ''
}
}
},
methods: {
onFileChange (e) {
this.fax.files = e.target.files || e.dataTransfer.files
if (!this.fax.files.length) {
return
}
console.log(this.fax.files)
}
},
created () {
this.$store.dispatch('setUserDid')
}
}
</script>
<template>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" multiple #change="onFileChange">
<input type="text" name="group" >
<ul>
<li v-for="file in fax.files">
{{ file.name }}
</li>
</ul>
</template>
Upto now, I can get file names displayed on my page using {{fax.files}}. How to make post request so that i can catch the file from my server side (API endpoint)? I tried googling and coding but i could not able to do.
Ok I managed to get this working. Before the file upload I had an array that I was posting via Ajax as you can see below.
I modified it to look like the below in order handle file uploads.
Basically you need to send through a FormData object when uploading files. Uses a FormData object by default when submitting a form - but when only posting a array you need to first append those array values to the FormData object.
You should be able to make sense of the code below...
var formData = new FormData();
jQuery.each(this.comment.file, function(i, file) {
formData.append('file[]', file);
});
formData.append('body', this.comment.body);
formData.append('comments_room_id', this.comment.comments_room_id);
formData.append('id', this.comment.id);
formData.append('name', this.comment.name);
this.$http.post('/api/comment/store', formData).then(function (response) {

How to save Facebook user data to MySql database with Angular and Ionic

I am working an an Ionic app where I implement native Facebook login (followed this tutorial -> https://ionicthemes.com/tutorials/about/native-facebook-login-with-ionic-framework). As you can see the Facebook data now gets stored in local storage. I need to save this data in my MySql database.
I got this to work without any issues. Now I want to store the Facebook user data to my MySql database.
Basically I am not sure where to place my http request to pass the data along to my database or how to even do it code wise.
I should mention that I have a backend already setup (which is coded with bootstrap, html, css, js php and mysql).
So the url for my users would be this: http://www.xxxxx.com/user.php
Part of my controller code:
app.controller('LoginCtrl', function($scope, $state, $q, UserService, $ionicLoading) {
// This is the success callback from the login method
var fbLoginSuccess = function(response) {
if (!response.authResponse){
fbLoginError("Cannot find the authResponse");
return;
}
var authResponse = response.authResponse;
getFacebookProfileInfo(authResponse)
.then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
});
$ionicLoading.hide();
$state.go('app.dashboard');
}, function(fail){
// Fail get profile info
console.log('profile info fail', fail);
});
};
// This is the fail callback from the login method
var fbLoginError = function(error){
console.log('fbLoginError', error);
$ionicLoading.hide();
};
// This method is to get the user profile info from the facebook api
var getFacebookProfileInfo = function (authResponse) {
var info = $q.defer();
facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null,
function (response) {
console.log('logging facebook response',response);
info.resolve(response);
},
function (response) {
console.log(response);
info.reject(response);
}
);
return info.promise;
};
//This method is executed when the user press the "Login with facebook" button
$scope.facebookSignIn = function() {
facebookConnectPlugin.getLoginStatus(function(success){
if(success.status === 'connected'){
// The user is logged in and has authenticated your app, and response.authResponse supplies
// the user's ID, a valid access token, a signed request, and the time the access token
// and signed request each expire
console.log('getLoginStatus', success.status);
// Check if we have our user saved
var user = UserService.getUser('facebook');
if(!user.userID){
getFacebookProfileInfo(success.authResponse)
.then(function(profileInfo) {
// For the purpose of this example I will store user data on local storage
UserService.setUser({
authResponse: success.authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large"
});
$state.go('app.dashboard');
}, function(fail){
// Fail get profile info
console.log('profile info fail', fail);
});
}else{
$state.go('app.dashboard');
}
} else {
// If (success.status === 'not_authorized') the user is logged in to Facebook,
// but has not authenticated your app
// Else the person is not logged into Facebook,
// so we're not sure if they are logged into this app or not.
console.log('getLoginStatus', success.status);
$ionicLoading.show({
template: 'Logging in...'
});
// Ask the permissions you need. You can learn more about
// FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4
facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError);
}
});
};
})
My service.js code (local storage)
angular.module('Challenger.services', [])
.service('UserService', function() {
// For the purpose of this example I will store user data on ionic local storage but you should save it on a database
var setUser = function(user_data) {
window.localStorage.starter_facebook_user = JSON.stringify(user_data);
};
var getUser = function(){
return JSON.parse(window.localStorage.starter_facebook_user || '{}');
};
return {
getUser: getUser,
setUser: setUser
};
});
My recommendation is to simply use a JSON ajax PUT or POST from JavaScript. For example, assuming a backend host of example.com
Add a CSP to the Ionic HTML such as:
<meta http-equiv="Content-Security-Policy" content="default-src http://example.com; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
Add the domain to the whitelist in the Cordova config.xml:
<access origin="http://example.com" />
Then you can call PHP from JavaScript with ajax in your angular controller (I used jQuery here but you can use any JavaScript ajax library):
var data = {
authResponse: authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
};
$.post( "http://example.com/login.php", data, function(returnData, status) {
console.log('PHP returned HTTP status code', status);
});
Finally, on the PHP side — e.g. login.php — access the post data with $_POST['userId'], $_POST['email'], etc.
I guess that you have all your codes ready, but just not sure where is the best place to locate your codes. There is nice linker where has clear instruction about how to layout your php project structure: http://davidshariff.com/blog/php-project-structure/, hope this can give a kind of help.

Categories