Can't upload image only on mobile device Laravel + Vue - javascript

I read about this on some posts on the stack, but I still do not see the same case as mine. I can not upload the image on phone device. I do not see why I do not have a console to see error. I'll show you the code, so someone who is experienced can see the error.
Laravel code to upload image:
public function uploadImage($car, $images)
{
$fileName = Carbon::now()->timestamp . $images->getClientOriginalName();
$path = $images->move(public_path('public/images'), $fileName);
if (!$path) {
return response()->json(['message' => 'An error has accured'], 500);
}
$carImage = new CarImages ([
'path' => 'public/images/' . $fileName
]);
$car->images()->save($carImage);
return $carImage;
}
Laravel code for store form with image:
public function store(CarRequest $request)
{
$file = null;
if ($request->has('picture')) {
$file = $request->file('picture');
}
$user = auth()->user();
if ($user) {
$car = Car::create([
'car_type' => $request->input('car_type'),
'mark' => $request->input('mark'),
'model' => $request->input('model'),
'user_id' => $user->id
]);
}
if (!$car) {
return response()->json(['message' => 'Oooops, something went wrong'], 500);
}
if ($file) {
$carImage = $this->uploadImage($car, $file);
}
Mail::to($user->email)->send(new NotifyNewCarUpload($user, $car));
return response()->json([
'message' => 'Your car has been successfully added',
'car' => $car,
'user' => $user
], 201);
}
In CarRequest for upload for car i have:
'car_type' => 'required',
'mark' => 'required',
'model' => 'required',
'picture' => 'required|image'
In Vue.js insert car I have:
<form enctype="multipart/form-data" accept-charset="utf-8"
#submit.prevent="submit">
...
...
<div class="col-3 insert-vehicle-right">
<div :class="{ 'error': errors.has('file') }" v-if="!imgSrc" class="image-upload-holder"></div>
<img :class="{ 'error': errors.has('file') }" v-if="imgSrc" class="uploaded-image" :src="imgSrc" alt="uploaded image"/>
<div class="upload-btn-wrapper">
<button class="btn action-btn">Upload Photo</button>
<input name="file"
v-validate="'required'"
type="file"
#change="onFileChange"/>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<button type="submit" class="btn action-btn save-btn">Save</button>
</div>
</form>
Vue.js javascript code for upload and preview image code:
onFileChange(event) {
this.picture = event.target.files[0];
const file = event.target.files[0];
this.imgSrc = URL.createObjectURL(this.picture);
},
And i have formData code for post that code:
...
...
formdata.append('picture', this.picture);
It's not working on mobile phones. Does anyone recognize the reason?
All my pictures are stored in the laravela folder public/public/images and work good on web browser (destop and laptop device). Also i have table for storing path images.. Only for phone device not work. Help?

Okey problem was be in php.ini configuraction and max_size_upload file. I only set more than 2mb images file and work perfecty.
#thanks Rasa

Related

Create post and upload image with Ajax (axios) in Wordpress

So I want my users to be able to create a post in the frontend and upload an image with a form I've created.
When the image is uploaded I want to update an ACF-field with the uploaded image.
I've seen some posts on this but none of them are explained any good.
I want to use Ajax and I want to use axios, so please no jQuery. I also use Qs.
The image itself is never uploaded but the file name is inserted in the media library.
Thank you!
HTML
<form enctype="multipart/form-data" method="post" id="register-store-form">
<fieldset class="store-images mb-3">
<label for="store-images">Add images</label>
<input type="file" id="store_images" name="store_images" accept="image/png, image/jpeg">
</fieldset>
<button class="btn btn-primary" id="update-store">Save store</button>
</form>
JS
const Qs = require('qs');
const axios = require('axios');
const saveStoreBtn = document.querySelector('#update-store');
const addStore = document.querySelector('#add-one-more-store');
function saveStore(e) {
const storeName = document.querySelector('#store-name');
const storeImages = document.querySelector('#store_images');
const storeImageFile = storeImages.files[0];
const ajaxData = {
action : 'create_store',
security : shkGlobal.addStore,
name : storeName.value,
image_name : storeImageFile.name,
image_type : storeImageFile.type,
description : storeDescription.value
};
axios.post(shkGlobal.adminUrl, Qs.stringify(ajaxData))
.then(function(response) {
saveStoreBtn.innerHTML = "Thank you";
})
.catch(err => console.log('Not working', err));
};
updateStoreBtn.addEventListener('click', saveStore);
PHP
function create_store() {
check_ajax_referer('add_store', 'security');
$name_value = $_POST['name'];
$image_name = $_POST['image_name'];
$image_type = $_POST['image_type'];
$post_data = array(
'post_type' => 'store',
'post_title' => htmlentities($name_value),
'post_content' => $_POST['description'],
'post_status' => 'draft'
);
$post_id = wp_insert_post( $post_data );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES[$image_name];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ($movefile) {
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'].'/'.$image_name,
'post_mime_type' => $image_type,
'post_title' => $image_name,
'post_content' => 'File '.$image_name,
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $movefile['file']);
update_field('field_602019eba7767', $attach_id, $post_id);
}
echo json_decode($response);
exit;
}
add_action('wp_ajax_create_store', 'create_store');
add_action('wp_ajax_nopriv_create_store', 'create_store');
There are two problems in your case, first one that you are uploading multiple files, so structure of $_FILES will be different. Second one is that you specified store_images instead store_images[] for multiple file upload.
So in html change <input type="file" name="store_images" multiple> to <input type="file" name="store_images[]" multiple>
And in php, change your code accordingly to example below.
$files = $_FILES['store_images];
foreach ($files as $key => $value) {
if ($files['name']) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
wp_handle_upload($file);
}
}
}

Import Excel with vue and laravel

can you help me to import excel into my program? i use maatwebsite/excel for uploading excel file.
So, i have
BarangController.php
public function import(Request $request)
{
// $path = $request->file('excel')->getRealPath();
$data = Excel::load($request->file('excel'))->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['nama_barang' => $value->nama_barang];
}
if(!empty($arr)){
return $arr;
}
}
}
Index.vue (modal)
<!-- Modal body -->
<div class="modal-body">
<div class="input-group">
<input #change="uploadExcel" id="excel" type="file" class="custom-file-input">
<label class="custom-file-label" for="excel">{{ fileName }}</label>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button #click="importExcel" type="button" class="btn btn-primary float-left">Import</button>
<button type="button" class="btn btn-danger float-right" data-dismiss="modal">Batal</button>
</div>
Index.vue (methods js)
importExcel() {
this.$Progress.start();
this.import.post('/api/barang/import').then((data) => {
console.log(data.data);
this.$Progress.finish();
}).catch(() => {
this.$Progress.fail();
})
},
uploadExcel(e) {
let file = e.target.files[0];
let reader = new FileReader();
// console.log(file);
if(file['type'] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
this.fileName = file['name'];
//this.import.excel = file;
reader.onloadend = (file) => {
this.import.excel = reader.result;
}
reader.readAsDataURL(file);
//this.import.excel = file;
console.log(this.import.excel);
} else {
Swal.fire({
type: 'warning',
title: 'Format file salah'
})
}
},
And when i check in console log its not get an array result for excel, i hope you can help me, thanks
What if you directly return $data = Excel::load($request->file('excel'))->get(); in your import method of your controller? What does your console say then?

How to submit image input file with dropzone.js and php

I have a Wordpress website that users can submit posts from the front-end. Im trying to integrate dropzone.js so users can submit images via drag and drop and sort images from featured image and gallery images kinda like what craigslist has.
My question is how do I get the featured image to get added to a file input
<input id="fileUpload" type="file" name="feat-img" accept="image/*" value="">
and the gallery image get added to
<input id="gallery-photo-add" type="file" name="muti_files[]" accept="image/*" multiple>
Heres my code
Html
<div class="dropzone" drop-zone="" id="file-dropzone"></div>
<ul class="visualizacao sortable dropzone-previews" style="border:1px solid #000"></ul>
<div class="preview" style="display:none;">
<li>
<div class="dz-preview dz-file-preview">
<img data-dz-thumbnail />
<input id="fileUpload" type="file" name="feat-img" accept="image/*" value="">
<input id="gallery-photo-add" type="file" name="muti_files[]" accept="image/*" multiple>
</div>
</li>
</div>
Javascript
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>
<script type="text/javascript">
var $ = jQuery
$(document).ready(function(){
$('.sortable').sortable();
});
$.getScript('https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.0.1/min/dropzone.min.js',function(){
$('#file-dropzone').dropzone({
url: "/",
maxFilesize: 100,
paramName: "uploadfile",
maxThumbnailFilesize: 99999,
previewsContainer: '.visualizacao',
previewTemplate : $('.preview').html(),
init: function() {
this.on('completemultiple', function(file, json) {
$('.sortable').sortable('enable');
});
this.on('success', function(file, json) {
alert('aa');
});
this.on('addedfile', function(file) {
console.log('File1',file);
});
this.on('drop', function(file) {
console.log('File2',file);
});
}
});
});
$(document).ready(function() {});
</script>
PHP
if( ! empty( $_FILES ) ){
$featured_image = $_FILES['feat-img'];
$attachment_id = upload_user_file( $featured_image, $post_id);
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$filee = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $filee);
foreach ($_FILES as $filee => $array) {
$newupload = my_handle_attachment($filee, $post_id);
}
}
}
}
if ( ! empty( $_FILES['muti_files'] ) ) {
$files = $_FILES['muti_files'];
foreach ($files['name'] as $key => $value){
if ($files['name'][$key]){
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
}
$_FILES = array("muti_files" => $file);
$i=1;
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attachment_id = media_handle_upload($file, $post_id);
$vv .= $attachment_id . ",";
$i++;
}
update_post_meta($post_id, '_product_image_gallery', $vv);
}
}
All this works fine if i dont use dropzone.js and just the <input type="file"> here is a codepen so you can see what im trying to do https://codepen.io/T-SEA/pen/OdqQOw

Save path image with Ajax in Laravel

I can save all data varchar/text element from my form, but I can't save my path image.
Whats is wrong with my code?
Lets see my create.blade.php I can save value of var deadline but I can't save value of var path:
Form::open(array('url' => 'imagesLoker', 'files' => true))
<form class="form-horizontal">
<div class="box-body">
<div class="form-group">
{!!Form::label('Deadline Lowongan : ')!!}
{!!Form::date('deadline',null,['id'=>'deadline','class'=>'form-control','placeholder'=>'Deadline Lowongan'])!!}
</div>
<div class="form-group">
{!!Form::label('Image Lowongan : ')!!}
{!!Form::file('path') !!}
</div>
</div><!-- /.box-body -->
</form>
{!!Form::close()!!}
This is my Controller:
public function store(Request $request)
{
Lowongan::create($request->all());
return "data all";
}
This is my Ajax to create the data:
$("#createLoker").click(function(){
var datas = $('form').serializeArray();
var route = "http://localhost:8000/lowongan";
var token = $("#token").val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post(route,{
deadline: $("#deadline").val(),
path: $("#path").val()
}).done(function(result){
console.log(result);
});
});
I don't know this is important or no to setting parse data in my Modal, but I just put this code in my Modal:
class Lowongan extends Model
{
protected $table = 'Lowongan';
protected $fillable = ['path','deadline'];
public function setPathAttribute($path){
$this->attributes['path'] = Carbon::now()->second.$path->getClientOriginalName();
$name = Carbon::now()->second.$path->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($path));
}
}
And the last I set the directory to save the image. This is setting in the config/filesystem:
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path('imagesLoker'),
],
I can save the data deadline but no for image :( .. If there is any idea for how to save the image path, I will be pleased to know it.
In your form you have to allow file upload option in laravel like.
Form::open(array('url' => 'foo/bar', 'files' => true))
check the file upload section of laravel doc
Hope it helps..
please follow these steps
in view
change {!!Form::file('path') !!} to {!!Form::file('file') !!}
In controller
please note i have set the upload path to root/public/uploads/ folder
public function store(Request $request)
{
$file = Input::file('file');
$path = '/uploads/';
$newFileName = Carbon::now()->second.$file->getClientOriginalName(). '.' . $file->getClientOriginalExtension();
// Move the uploaded file
$upSuccess = $file->move(public_path() . $path, $newFileName);
$result = file_exists(public_path() . $path . $newFileName);
$fileData =[
'fileType' => $file->getClientOriginalExtension(),
'filePath' => substr($path, 1) . $newFileName
];
Input::merge(array('path' => $fileData["filePath"]));
Lowongan::create($request->all());
return "data all";
}

Angularjs Satellizer not returning email

I have an app build on angularjs, and laravel and for authentication I use Satellizer.
Currently the login work, but it only return display name. Here is the code:
satellizer.js
providers: {
facebook: {
name: 'facebook',
url: '/auth/facebook',
authorizationEndpoint: 'https://www.facebook.com/v2.3/dialog/oauth',
redirectUri: (window.location.origin || window.location.protocol + '//' + window.location.host) + '/',
requiredUrlParams: ['scope'],
scope: ['email'],
scopeDelimiter: ',',
display: 'popup',
type: '2.0',
popupOptions: { width: 580, height: 400 }
},
account.js
angular.module('MyApp')
.factory('Account', function($http) {
return {
getProfile: function() {
return $http.get('/api/me');
},
updateProfile: function(profileData) {
return $http.put('/api/me', profileData);
}
};
});
profile.js
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Profile</div>
<div class="panel-body">
<legend><i class="ion-clipboard"></i> Edit My Profile</legend>
<form method="post" ng-submit="updateProfile()">
<div class="form-group">
<label class="control-label">Profile Picture</label>
<img class="profile-picture" ng-src="{{user.picture || 'http://placehold.it/100x100'}}">
</div>
<div class="form-group">
<label class="control-label"><i class="ion-person"></i> Display Name</label>
<input type="text" class="form-control" ng-model="user.displayName" />
</div>
<div class="form-group">
<label class="control-label"><i class="ion-at"></i> Email Address</label>
<input type="email" class="form-control" ng-model="user.email" />
</div>
<button class="btn btn-lg btn-success">Update Information</button>
</form>
</div>
</div>
auth controller in laravel php
public function facebook(Request $request)
{
$accessTokenUrl = 'https://graph.facebook.com/v2.3/oauth/access_token';
$graphApiUrl = 'https://graph.facebook.com/v2.3/me';
$params = [
'code' => $request->input('code'),
'client_id' => $request->input('clientId'),
'redirect_uri' => $request->input('redirectUri'),
'client_secret' => Config::get('app.facebook_secret')
];
$client = new GuzzleHttp\Client();
// Step 1. Exchange authorization code for access token.
$accessToken = $client->get($accessTokenUrl, ['query' => $params])->json();
// Step 2. Retrieve profile information about the current user.
$profile = $client->get($graphApiUrl, ['query' => $accessToken])->json();
// Step 3a. If user is already signed in then link accounts.
if ($request->header('Authorization'))
{
$user = User::where('facebook', '=', $profile['id']);
if ($user->first())
{
return response()->json(['message' => 'There is already a Facebook account that belongs to you'], 409);
}
$token = explode(' ', $request->header('Authorization'))[1];
$payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256'));
$user = User::find($payload['sub']);
dd($user);
$user->facebook = $profile['id'];
$user->displayName = $user->displayName || $profile['name'];
$user->save();
return response()->json(['token' => $this->createToken($user)]);
}
// Step 3b. Create a new user account or return an existing one.
else
{
$user = User::where('facebook', '=', $profile['id']);
if ($user->first())
{
return response()->json(['token' => $this->createToken($user->first())]);
}
$user = new User;
$user->facebook = $profile['id'];
$user->displayName = $profile['name'];
$user->save();
return response()->json(['token' => $this->createToken($user)]);
}
}
Thanks!
In a new Facebook Graph API you should include email and other things you want to get in Graph Api url, take a look at this: https://developers.facebook.com/docs/graph-api/using-graph-api/v2.5
So in your case the solution will be to update your Api urls like this:
Update:
authorizationEndpoint: 'https://www.facebook.com/v2.3/dialog/oauth',
With:
authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',
And update this:
$accessTokenUrl = 'https://graph.facebook.com/v2.3/oauth/access_token';
$graphApiUrl = 'https://graph.facebook.com/v2.3/me';
With this:
$accessTokenUrl = 'https://graph.facebook.com/v2.5/oauth/access_token';
$graphApiUrl = 'https://graph.facebook.com/v2.5/me?fields=id,name,email,picture,first_name,last_name';

Categories