Import Excel with vue and laravel - javascript

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?

Related

Javascript Vue: Where does the variable 'e' in onFileChange(e) originate?

Javascript Vue: Where does the variable e in onFileChange(e) originate?
In the following code, there is a variable e in onFileChange(e), where does it originate? It is never declared or imported in the code, so how can it be valid?
Any help would be greatly appreciated.
<template>
<div class="container" style="margin-top: 50px;">
<div class="text-center">
<h4>File Upload with VueJS and Laravel</h4>
<br />
<div style="max-width: 500px; margin: 0 auto;">
<div v-if="success !== ''" class="alert alert-success" role="alert">
{{success}}
</div>
<form #submit="submitForm" enctype="multipart/form-data">
<div class="input-group">
<div class="custom-file">
<input
type="file"
name="filename"
class="custom-file-input"
id="inputFileUpload"
v-on:change="onFileChange"
/>
<label class="custom-file-label" for="inputFileUpload"
>Choose file</label
>
</div>
<div class="input-group-append">
<input type="submit" class="btn btn-primary" value="Upload" />
</div>
</div>
<br />
<p class="text-danger font-weight-bold">{{filename}}</p>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log("Component successfully mounted.");
},
data() {
return {
filename: "",
file: "",
success: ""
};
},
methods: {
onFileChange(e) {
//console.log(e.target.files[0]);
this.filename = "Selected File: " + e.target.files[0].name;
this.file = e.target.files[0];
},
submitForm(e) {
e.preventDefault();
let currentObj = this;
const config = {
headers: {
"content-type": "multipart/form-data",
"X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')
.content
}
};
// form data
let formData = new FormData();
formData.append("file", this.file);
// send upload request
axios
.post("/store_file", formData, config)
.then(function(response) {
currentObj.success = response.data.success;
currentObj.filename = "";
})
.catch(function(error) {
currentObj.output = error;
});
}
}
};
</script>
That declaration is triggered by your template, where you are binding change event to the method. The whole event as parameter gets passed to the method, Refer this section of Vue docs for better information https://v2.vuejs.org/v2/guide/events.html#Method-Event-Handlers
When a variable is called e it is usually the event. You can always console.log(e) and read its properties in the browser console.
But according to this example e is the file that is uploaded:
methods: {
thumbUrl (file) {
return file.myThumbUrlProperty
},
onFileChange (file) {
// Handle files like:
this.fileUploaded = file
}
}
onFileChange(e) has e as event related to the dom. Since while assigning the function in html if there is no parameter passed, the event as a parameter is automatically passed by javaScript.
The declaration onFileChange(e) {
declares a function with the name onFileChange that takes a single parameter e. That is what introduces the variable into the function body.

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

How can i add/send multiple records in asp.net MVC using jQuery?

I want to send multiple records in the database using javascript in asp.net mvc i tried many different ways but all in vain. here I have the best code which can send the data to the controller but the file is not sending.
I search different ways i have found one is with FormData but i am unable to handle that in this context.
Controller:
public ActionResult SaveAllFeedback(FEEDBACKVM[] fEEDBACKs)
{
try
{
if (fEEDBACKs != null)
{
FEEDBACK fEEDBACK = new FEEDBACK();
foreach (var item in fEEDBACKs)
{
fEEDBACK.DATE = item.DATE;
fEEDBACK.COMMENT = item.COMMENT;
fEEDBACK.STUDENTID = item.STUDENTID;
fEEDBACK.TEACHERID = db.TEACHERs.Where(x => x.EMAIL == User.Identity.Name).FirstOrDefault().ID;
if (item.HOMEWORK != null)
{
fEEDBACK.HOMEWORK = SaveToPhysicalLocation(item.HOMEWORK);
}
db.FEEDBACKs.Add(fEEDBACK);
}
db.SaveChanges();
return Json("Done", JsonRequestBehavior.AllowGet);
}
return Json("Unable to save your feedback! Please Provice correct information", JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json("Unable to save your feedback! Please try again later.", JsonRequestBehavior.AllowGet);
}
}
ViewPage:
<form>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<input name="DATE" id="DATE" type="date" class="form-control" />
</div>
<table class="table table-responsive table-hover" id="table1">
<thead>
<tr class="bg-cyan">
<th></th>
<th>RollNumber</th>
<th>Comment</th>
<th>Homework</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.students)
{
<tr>
<td>
<input name="STUDENTID" type="text" value="#item.Key" hidden="hidden" />
</td>
<td>
<input name="STUDENTROLLNUMBER" type="text" value="#item.Value" class="form-control" readonly="readonly" />
</td>
<td>
<input name="COMMENT" type="text" class="form-control" />
</td>
<td>
<input name="HOMEWORK" type="file" class="form-control" />
</td>
</tr>
}
</tbody>
</table>
<div class="form-group">
<div class="col-md-10">
#Html.ValidationMessage("ErrorInfo", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button id="saveButton" type="submit" class="btn btn-danger">Save Attendance</button>
</div>
</div>
</form>
Script:
<script>
//After Click Save Button Pass All Data View To Controller For Save Database
function saveButton(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("SaveAllFeedback", "Teacherss")',
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveButton").click(function (e) {
e.preventDefault();
var formData = new FormData();
var arr = [];
arr.length = 0;
$.each($("#table1 tbody tr"), function () {
//arr.push({
// //DATE: $("#DATE").val(),
// //STUDENTID: $(this).find('td:eq(0) input').val(),
// //COMMENT: $(this).find('td:eq(2) input').val(),
// //HOMEWORK: $(this).find('td:eq(3) input').val()
// });
formData.append("DATE", $("#DATE").val());
formData.append("STUDENTID", $(this).find('td:eq(0) input').val());
formData.append("COMMENT", $(this).find('td:eq(2) input').val());
formData.append("HOMEWORK", $(this).find('td:eq(3) input')[0].files[0]);
});
var data = JSON.stringify({
fEEDBACKs: formData
});
$.when(saveButton (data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
I just want to send multiple records with the file to the database
are you sure you want send the files???? if yes then
Your form tag should be look like this
<form id="yourid" action="youraction" enctype="multipart/form-data">
Form Component
</form>
NOTE:- enctype="multipart/form-data" tag is important
and then controller should be look like this
public ActionResult YourController(FormCollection data)
{
if (Request.Files.Count > 0)
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//you can save the file like this
string path = Server.MapPath("~/Yourpath/FileName" + fileName.Substring(fileName.LastIndexOf('.')));
file.SaveAs(path);
//or you can load it to memory like this
MemoryStream ms = new MemoryStream();
file.InputStream.CopyTo(ms);
//use it how you like
}
}
return View();
}

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

Submitting form in Vue.js with ajax

I'm really stuck on how I would work with submitting a form that makes an ajax request using Vue.js and vue-resource then using the response to fill a div.
I do this from project to project with js/jQuery like this:
view in blade
{!! Form::open(['route' => 'formRoute', 'id' => 'searchForm', 'class' => 'form-inline']) !!}
<div class="form-group">
<input type="text" name="id" class="form-control" placeholder="id" required="required">
</div>
<button type="submit" class="btn btn-default">Search</button>
{!! Form::close() !!}
js/jquery
var $searchForm = $('#searchForm');
var $searchResult = $('#searchResult');
$searchForm.submit(function(e) {
e.preventDefault() ;
$.get(
$searchForm.attr('action'),
$searchForm.serialize(),
function(data) {
$searchResult.html(data['status']);
}
);
});
What I've done/tried so far in Vue.js:
view in blade
{!! Form::open(['route' => 'formRoute', 'id' => 'searchForm', 'class' => 'form-inline']) !!}
<div class="form-group">
<input type="text" name="id" class="form-control" placeholder="id" required="required">
</div>
<button type="submit" class="btn btn-default" v-on="click: search">Search</button>
{!! Form::close() !!}
vue/js
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
new Vue({
el: '#someId',
data: {
},
methods: {
search: function(e) {
e.preventDefault();
var req = this.$http.get(
// ???, // url
// ???, // data
function (data, status, request) {
console.log(data);
}
);
}
}
});
I'm wondering if it's possible to use components when dealing with the response to output the response data to a div?
Just to summarise everything:
How do I submit a form using vue js and vue-resource instead of my usual jQuery way?
Using a response from ajax, how can I output data into a div preferably using components?
I used this approach and worked like a charm:
event.preventDefault();
let formData = new FormData(event.target);
formData.forEach((key, value) => console.log(value, key));
In order to get the value from input you have to use v-model Directive
1. Blade View
<div id="app">
<form v-on="submit: search">
<div class="form-group">
<input type="text" v-model="id" class="form-control" placeholder="id" required="required">
</div>
<input type="submit" class="btn btn-default" value="Search">
</form>
</div>
<script type="text/javascript">
// get route url with blade
var url = "{{route('formRoute')}}";
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
var app = new Vue({
el: '#app',
data: {
id: '',
response: null
},
methods: {
search: function(event) {
event.preventDefault();
var payload = {id: this.id};
// send get request
this.$http.get(url, payload, function (data, status, request) {
// set data on vm
this.response = data;
}).error(function (data, status, request) {
// handle error
});
}
}
});
</script>
If you want to pass data to component the use 'props' see docs for more info
http://vuejs.org/guide/components.html#Passing_Data_with_Props
If you want use laravel and vuejs together, then checkout
https://laracasts.com/series/learning-vuejs
Add v-model="id" on your text input
then add it to your data object
new Vue({
el: '#someId',
data: {
id: ''
},
methods: {
search: function(e) {
e.preventDefault();
var req = this.$http.get(
'/api/search?id=' + this.id,
function (data, status, request) {
console.log(data);
}
);
}
}
});
It’s better to remove v-on="click: search" and add v-on="submit: search" on the form tag.
You should add method="GET" on your form.
Make sure you have #someId in your html markup.

Categories