Redirect file uploading request in Fine Uploader - javascript

I am using Fine Uploader for uploading multiple files.
It's working fine.
But i want a little bit change.
I have a file name upload.php in which i have written a file uploading script in database.
I just want that after hitting upload button the request will go to my upload.php file and the files will be uploaded accordingly.
How i can achieve this ?
index.php
<script type="text/template" id="qq-template-manual-trigger">
<div class="buttons">
<div class="qq-upload-button-selector qq-upload-button">
<div>Select files</div>
</div>
<button type="button" id="trigger-upload" class="btn btn-primary">
<i class="icon-upload icon-white"></i> Upload
</button>
</div>
</script>
Javascript
<script>
var manualUploader = new qq.FineUploader({
element: document.getElementById('fine-uploader-manual-trigger'),
template: 'qq-template-manual-trigger',
request: {
endpoint: '/server/upload.php'
},
thumbnails: {
placeholders: {
waitingPath: '/source/placeholders/waiting-generic.png',
notAvailablePath: '/source/placeholders/not_available-generic.png'
}
},
autoUpload: false,
debug: true
});
qq(document.getElementById("trigger-upload")).attach("click", function() {
manualUploader.uploadStoredFiles();
});
</script>
upload.php
<?php
require_once './include/db_connection.php';
if(!empty($_FILES)){
$targetDir = "upload/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile))
{
//insert file information into db table
$sql = mysqli_query($link,"INSERT INTO files (file_name, uploaded) VALUES('".$fileName."','".date("Y-m-d H:i:s")."')");
}
else
{
echo 'Query not working';
}
}

Related

how can i fetch a file that i have already upload and i want to delete it and replace it using bootstrap file input

i want to fetch the file based on my applications_id and i want to see it in the bootstrap file input and i want to delete it and replace with a new file. how can i do it. below is what i have tried .can anyone help me .i am stuck.
this is my contoller function SoleProprietorController.php
public function uploadImages(Request $request, $applications_id)
{
$applications = new Applications;
// $KRAPIN = Input::get('KRA_unique_field');
$applications_id = Input::get('applications_id_unique_field');
if ($request->hasFile('breg_cert')) {
if ($request->file('breg_cert')->isValid()) {
// request()->breg_cert->move(public_path('breg_cert'), $imgName);
// $imgName = basename($request->breg_cert->store(public_path('breg_cert')));
$imgName = basename($request->breg_cert->move(public_path('breg_cert')));
$applications->breg_cert = $imgName;
}
return response()->json(['uploaded' => '/breg_cert/'.$imgName]);
}
}
this my web.php
Route::post('/uploadImages/{applications_id}', 'SoleProprietorController#uploadImages')->name('home');
this is my bootstrap file in my blade
<div class="col-md-4 mb-3">
<label for="validationServer023">Upload Business Registration Document</label>
<div class="form-group">
<div content="{{ csrf_token() }}" class="input-group input-file" name="Fichier1">
<input id="file-0a" name="breg_cert" value="" class="file" accept="text" type="file"> <br />
</div>
</div>
</div>
<script>
$("#file-0a").fileinput({
initialPreview: [
"<img src='/images/php' class='file-preview-image'>",
],
showUpload: true,
showRemove: true,
showCaption: true,
showPreview: true,
showClose: false,
autoOrientImage: true,
showUploadedThumbs: false,
uploadAsync: false,
uploadUrlThumb: false,
deleteUrl: "/public/KFS_Business_Registration_Certificates",
uploadUrl: "/uploadImages/{applications_id}",
// dataUrl: "/breg_cert/",
// uploadUrl: '/public/KFS_Business_Registration_Certificates', // you must set a valid URL here else you will get an error
theme: 'fa',
uploadExtraData: function() {
return {
_token: "{{ csrf_token() }}",
};
},
allowedFileExtensions: ['jpg', 'png', 'gif', 'pdf', 'jpeg'],
overwriteInitial: false,
maxFileSize: 500,
maxFilesNum: 10,
//allowedFileTypes: ['image', 'video', 'flash'],
slugCallback: function (filename) {
return filename.replace('(', '_').replace(']', '_');
}
});
</script>
1.Use code like this to store uploaded file and associate it with your Applications
if ($request->hasFile('breg_cert')) {
if ($request->file('breg_cert')->isValid()) {
$imgName = basename($request->breg_cert->store(public_path('breg_cert')));
$applications->breg_cert = $imgName;
}
}
https://laravel.com/docs/5.8/requests#storing-uploaded-files
To store an uploaded file, you will typically use one of your configured filesystems. The UploadedFile class has a store method which will move an uploaded file to one of your disks, which may be a location on your local filesystem or even a cloud storage location like Amazon S3.
The store method accepts the path where the file should be stored relative to the filesystem's configured root directory. This path should not contain a file name, since a unique ID will automatically be generated to serve as the file name.
To handle delete/replace create a corresponding controller method and POST route and then provide the route to deleteUrl option.
In the above method check the filename associated and unlink it. (actual code depends on what dd($request); output)
To show stored image as preview add option to $("#file-0a").fileinput({
initialPreview: [
"<img src='/images/path-to.jpg' class='file-preview-image'>",
],

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

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

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?

error upload files, php and angularjs connexion aborted

i'm trying to upload files using angularJs and PHP.
the exact error message is like that:
ionic.bundle.js:26799 TypeError: Cannot read property 'state_code' of null
at controllers.js:1718
at services.js:298
at processQueue (ionic.bundle.js:29132)
at ionic.bundle.js:29148
at Scope.$eval (ionic.bundle.js:30400)
at Scope.$digest (ionic.bundle.js:30216)
at Scope.$apply (ionic.bundle.js:30508)
at done (ionic.bundle.js:24829)
at completeRequest (ionic.bundle.js:25027)
at XMLHttpRequest.requestError (ionic.bundle.js:24978)
html form:
<div class="footer row">
<div class="text-center col col-50">
<div id="FileUpload">
<input type="file" accept="image/*;capture=camera" id="BrowserHidden" ng-model="upload_file"/>
<div class="text-center">
<button class="button custom-button" type="submit">
Charger un fichier
</button>
</div>
</div>
</div>
<div class="text-center col col-50">
<button class="button custom-button" ng-click="SubmitUpload();">
Suivant
</button>
controllers.js looks like that at 1718 :
if (document.getElementById("BrowserHidden") != undefined) {
document.getElementById("BrowserHidden").onchange = function () {
var reader = new FileReader();
reader.onload = function (e) {
// get loaded data and render thumbnail.
document.getElementById("image").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(this.files[0]);
$scope.fileUploaded = this.files[0];
var image_name=this.files[0].name;
$scope.image_name=image_name;
localStorage.setItem("piece1", $scope.image_name);
};
}
$scope.SubmitUpload = function () {
if ($scope.fileUploaded == undefined) {
$ionicPopup.alert({
title: "Alert",
template: "Veuillez sélectionner une photo de votre carte d'identité ou passeport"
});
} else {
UploadService.uploadFile($scope.fileUploaded, getLocalItem("id_user", localStorageService), function (data) {
ligne 1718-> console.log(data)
if (data.state_code == 200) {
//$state.go('success_upload');
$state.go('signaletique_upload_2');
} else {
$ionicPopup.alert({
title: "Alert",
template: data.message
});
}
});
}
}
service.js
.factory('UploadService', function ($http, $ionicLoading, Upload) {
return {
uploadFile: function (_photo, _formID, callback) {
$ionicLoading.show();
Upload.upload({
url: UPLOAD_FILE,
headers: {
'Content-Type':'application/x-www-form-urlencoded'
// or 'Content-Type':'application/json'
},
data: {photo: _photo, 'user_id': _formID}
}).then(function (resp) {
ligne 298-> callback(resp.data);
$ionicLoading.hide();
}, function (resp) {
callback(resp.data);
$ionicLoading.hide();
}, function (evt) {
});
}
}
})
function.js
var UPLOAD_FILE = URL_RACINE +'php/ws_upload_file.php';
ws_upload_file.php
include_once 'config.php';
$id_user = $data['user_id'];
$uploads_dir = 'uploads';
$tmp_name = $_FILES["photo"]["tmp_name"];
$name = $_FILES["photo"]["name"];
$ext = pathinfo($name, PATHINFO_EXTENSION);
if(!in_array($ext,['png','jpg','jpeg'])){
echo json_encode(array('status'=>'Error','state_code' => '101','message'=>'fichier invalide'));
die;
}else{
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
evrything used to work fine , but now i get an error off connexion
aborted ,when i try to uplaod file. so i figure out a solution is to
add the host name before calling the ws php to upload file
exp(http://195.25.55.21:81/php/ws_upload.php) but this work only for
my local machine others get connection forbiden even that they can
access to the domaine they get only error permission when they try to
upload files.
To make it more confusing when i try to call the function like
that('/php/ws_upload.php') only files who has small taill accepted ,
even in the php.ini by default i get 2M , note with this method i get
connection aborted failed to load ressource /php/ws_upload.php.
i downlond the project and i tried in my machine evrything works fine
, means that it's not an eror in my code
i'm just unsure as to what could be stopping the upload,quiring minds want to know. Thank you

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";
}

Categories