I have tried majority of other questions here and other solutions and nothing has worked so far.
What I am trying to accomplish is upload images before Laravel's validation takes place, obviously I can't use the create function because it wont be hit until validation succeeds so I have made a custom function to do the file saving server side and trying to use Ajax to call that function every time a file is selected.
Current issue: doesn't seem like my Ajax is running on debugging its being skipped over,
second issue: I have a csrf token in my master template do i still need to add the ajax setup? if so is the way i am doing it correct.
Route:
Route::post('/upload', 'UploadController#uploadSubmit');
View:
<div>
<input type="file" id="fileupload" name="photos[]" data-url="/upload" multiple />
<br />
<div id="files_list"></div>
<p id="loading"></p>
<input type="hidden" name="file_ids" id="file_ids" value="" />
</div>
Ajax call:
$(document).ready(function(){
$("input").change(function(){
alert('triggered');
debugger;
$('#fileupload').fileupload({
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $(meta[name="csrf-token"]).attr('content')
}
dataType: 'json',
add: function (e, data) {
$('#loading').text('Uploading...');
data.submit();
},
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').html(file.name + ' (' + file.size + ' KB)').appendTo($('#files_list'));
if ($('#file_ids').val() != '') {
$('#file_ids').val($('#file_ids').val() + ',');
}
$('#file_ids').val($('#file_ids').val() + file.fileID);
});
$('#loading').text('');
}
});
});
});
});
Controller:
public function uploadSubmit(Request $request){
$files = [];
dd(request());
foreach($learnerFiles as $key => $learnerFile){
if(count($learnerFile) > 0){
$path = $learnerFile->storeAs('public/uploads/learners', request('idNumber').'_'.$key.'.'.$learnerFile->extension());
$search = 'public/' ;
$trimmed = str_replace($search, '', $path) ;
//dd($learnerFiles);
$file = FileUpload::create([
'user_id' => $learner->id,
'file_name' => $key,
'path' => $trimmed
]);
}
else{
}
$file_object = new \stdClass();
$file_object->name = $key;
$file_object->size = round(Storage::size($path) / 1024, 2);
$file_object->fileID = $learner->id;
$files[] = $file_object;
}
return response()->json(array('files' => $photos), 200);
}
I'm using the following method to upload images using Ajax call and Laravel back-end.
var uploader = $('#image-uploader[type="file"]');
var data = new FormData();
$.each(uploader.files, function() {
data.append('image[]', this);
});
data.append('_token', $('[name="csrf-token"]').attr('content'));
var url = '/upload'; //Or any target path with post method
$.ajax({
url: url,
method: 'POST',
data: data,
processData: false,
contentType: false,
success: function(data) {
alert('succeed');
}
});
Consider you can access to image files in server-side using $_POST['image] array.
Hope this helps you.
Related
I am not able to upload any images after second input. I can only upload the first input. The inputs are created dynamically when another input value is added. Below is the code:
\\ jquery //
function storeupdate(){
$.ajax({
type:"POST",
url:"<?php echo base_url(); ?>updatestore",
data:$("#mainstore").serialize(),
success: function(response){
var data = new FormData();
input = document.getElementById('file');
for(var i = 0; i < input.files.length; i++)
{
data.append('images[]', document.getElementById('file').files[i]);
}
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>storeupload',
cache: false,
contentType: false,
processData: false,
data : data,
success: function(result){
console.log(result);
},
error: function(err){
console.log(err);
}
});
swal('Successful!', 'Data has been saved!', 'success');
//window.location.reload();
},
error: function() {
swal("Oops", "We couldn't connect to the server!", "error");
}
});
return false;
};
\\ view //
<input type="file" name="images[]" id="file" class="file" accept="image/*;capture=camera" multiple="multiple" />
<button type="button" class="btn btn-success save" id="save" name="save" onclick="storeupdate();" disabled>Save</button>
\\ controller //
public function storeupload()
{
$files= $_FILES;
$cpt = count ($_FILES['images']['name']);
for($i = 0; $i < $cpt; $i ++) {
$_FILES['images']['name'] = $files['images']['name'][$i];
$_FILES['images']['type'] = $files['images']['type'][$i];
$_FILES['images']['tmp_name'] = $files['images']['tmp_name'][$i];
$_FILES['images']['error'] = $files['images']['error'][$i];
$_FILES['images']['size'] = $files['images']['size'][$i];
$this->upload->initialize ( $this->set_upload_options1() );
$this->upload->do_upload("images");
$fileName = $_FILES['images']['name'];
$images[] = $fileName;
}
}
I made and tested a little sample of code so that you can see what's wrong. You have a few things wrong. First thing I would recommend is actually using jQuery. Your code is obviously using jQuery, but you have all kinds of vanilla JS that can be simplified:
$(document).ready(function(){
$('#save').on('click', function(){
var fileInput = $('#file_input')[0];
if( fileInput.files.length > 0 ){
var formData = new FormData();
$.each(fileInput.files, function(k,file){
formData.append('images[]', file);
});
$.ajax({
method: 'post',
url:"/multi_uploader/process",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
}else{
console.log('No Files Selected');
}
});
});
Notice that I hard coded in the ajax URL. The controller I used for testing was named Multi_uploader.php.
Next is that in your controller when you loop through the $_FILES, you need to convert that over to "userfile". This is very important if you plan to use the CodeIgniter upload class:
public function process()
{
$F = array();
$count_uploaded_files = count( $_FILES['images']['name'] );
$files = $_FILES;
for( $i = 0; $i < $count_uploaded_files; $i++ )
{
$_FILES['userfile'] = [
'name' => $files['images']['name'][$i],
'type' => $files['images']['type'][$i],
'tmp_name' => $files['images']['tmp_name'][$i],
'error' => $files['images']['error'][$i],
'size' => $files['images']['size'][$i]
];
$F[] = $_FILES['userfile'];
// Here is where you do your CodeIgniter upload ...
}
echo json_encode($F);
}
This is the view that I used for testing:
<!doctype html>
<html>
<head>
<title>Multi Uploader</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="/js/multi_uploader.js"></script>
</head>
<body>
<form>
<input type="file" name="images[]" id="file_input" multiple />
<button type="button" id="save">Upload</button>
</form>
</body>
</html>
Finally, just to prove that the files were uploaded to the controller, and that I could use them with CodeIgniter, I send the ajax response as a json encoded array, and display it in the console. See the code comment where you would put your CodeIgniter upload code.
UPDATE (to show what to do with multiple file inputs) ---
If you want to have multiple file inputs, then that obviously changes your HTML and JS a bit. In that case, your HTML would have the multiple inputs:
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
<input type="file" name="images[]" class="file_input" multiple />
And your javascript needs to change to loop through each input:
$(document).ready(function(){
$('#save').on('click', function(){
var fileInputs = $('.file_input');
var formData = new FormData();
$.each(fileInputs, function(i,fileInput){
if( fileInput.files.length > 0 ){
$.each(fileInput.files, function(k,file){
formData.append('images[]', file);
});
}
});
$.ajax({
method: 'post',
url:"/multi_uploader/process",
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(response){
console.log(response);
}
});
});
});
A little more info about your comment regarding adding the details to your database ---
When you do an upload with CodeIgniter, there is a provided upload summary:
$summary = $this->upload->data();
This is an array of data that ends up looking like this:
$summary = array(
'file_name' => 'mypic.jpg',
'file_type' => 'image/jpeg',
'file_path' => '/path/to/your/upload/',
'full_path' => '/path/to/your/upload/jpg.jpg',
'raw_name' => 'mypic',
'orig_name' => 'mypic.jpg',
'client_name' => 'mypic.jpg',
'file_ext' => '.jpg',
'file_size' => 22.2
'is_image' => 1
'image_width' => 800
'image_height' => 600
'image_type' => 'jpeg',
'image_size_str' => 'width="800" height="200"'
);
So all you would have to do to add a record to your database is this after each upload:
$summary = $this->upload->data();
$this->db->insert('storefiles', array(
'Store_ID' => $_POST['storeid'],
'File_Name' => $summary['file_name'],
'Created' => date('Y-m-d h:i:s'),
'Modified' => date('Y-m-d h:i:s')
));
It's pretty easy to see that you could store a lot more than just the filename.
I know this question is old, but for people like me who encounter this error: is_uploaded_file() expects parameter 1 to be string, array given after using the Code Igniter file upload library within the loop like so:
for ( $i = 0; $i < count($var); $i++ )
{
// other codes here
// Do codeigniter upload
$this->upload->do_upload('images');
}
What you can do is to not put any params in the do_upload() function. Like so:
$this->upload->do_upload();
I'm working on a Laravel Spark project and I am trying to get a form to upload a folder to my S3 bucket. I have the form built:
<form enctype="multipart/form-data">
<input type="file" name="resume" v-model="form.resume">
<button #click="updateProfile">Update Profile</button>
</form>
Then I have a vue component set up to handle the form submit:
Vue.component('resume-links', {
template: '#edit-resume-links',
data() {
return {
form: new SparkForm({
resume: ''
})
};
},
methods: {
updateProfile() {
console.log(this.form.resume);
Spark.post('/route/to/controller', this.form).then(response => {
console.log(response);
});
}
}
});
Then in my laravel controller:
$resume = $request->file('resume');
$resumeFileName = time() . '.' . $resume->getClientOriginalExtension();
$s3 = \Storage::disk('s3');
$filePath = '/resumes/' . $resumeFileName;
$s3->put($filePath, file_get_contents($resume), 'public');
When I try to submit the form with a file it throws this error:
Call to a member function getClientOriginalExtension() on null
I have tried var_dumping $resume right after setting it to the file() and what I see outputted to the console is a bunch of js looking code
From everything that I reading it looks like file uploads with Laravel is super easy and I don't know why I am having this issue. Any assistance/advice would be appreciated! Thanks!
First of all, your file input needs to have the v-el attribute rather than v-model.
In your case it would be <input type="file" name="form" v-el:resume />.
Next, in your Vue component, you need to gather the FormData so that it becomes possible to send the file to the server. Files have to be handled slightly differently to plain text fields and such.
Add this to your methods object:
gatherFormData() {
const data = new FormData();
data.append('resume', this.$els.resume.files[0]);
return data;
}
In your updateProfile method you now need to send this data off to the server as a POST request.
updateProfile(e) {
e.preventDefault();
var self = this;
this.form.startProcessing();
$.ajax({
url: '/route/to/controller',
data: this.gatherFormData(),
cache: false,
contentType: false,
processData: false,
type: 'POST',
headers: {
'X-XSRF-TOKEN': Cookies.get('XSRF-TOKEN')
},
success: function (response) {
self.form.finishProcessing();
console.log(response)
},
error: function (error) {
self.form.setErrors(error.responseJSON);
}
});
},
Finally, in your controller method, you can now handle the file as normal
(e.g., $request->file('resume');)
Handling files with Laravel really is a breeze – you just need to make sure you're actually getting them to the server ;)
i have a problem in ajax, indeed, i try to send value with ajax to my upload function before submit.
But when i check the $_POST array in my php code, there is only the value of the form, and not from the ajax, and I don't know why.
Here is my code :
HTML:
<button id="btn_saisie" class="btn btn-app saver adddocu" ><i class="fa fa-save whiter"></i></button>
<form action="/uploader/adddocu" id="form_saisie" class="form_saisie" method="POST" enctype="multipart/form-data">
<input type="file" name="document" class="val_peage form-control form_num" id="document" data-rest="document" placeholder="Document">
<input type="text" name="description" class="val_parking form-control form_num" id="description" data-rest="description" placeholder="Description">
JS :
$( ".adddocu" ).click(function() {
if ($('#document').val() != "" && $('#description').val() != ""){
api_sendvalue_adddoc();
}
if ($('#document').val() == "")
alert('test');
else if ($('#description').val() == "")
alert('test2'); });
function api_sendvalue_adddoc(){
user = JSON.parse(sessionStorage.getItem('user'));
pays = localStorage.getItem("pays");
magasin = localStorage.getItem("magasin");
$.ajax({
type: 'POST',
url: '/uploader/adddocu',
data: {pays:pays, magasin:magasin},
success: function(data){
alert(data);
$("#form_saisie").submit();
console.log(data);
},
error: function(xhr){
alert(xhr.responseText);
console.log(xhr.responseText);
}
}); }
PHP:
public function adddocu(){
$path = './asset/upload/pdf/';
$path2 = '/asset/upload/pdf/';
$config['upload_path'] = $path;
$config['encrypt_name'] = false;
$config['file_ext_tolower'] = true;
$config['allowed_types'] = 'pdf';
// die(var_dump($_POST));
$this->load->library('upload', $config);
foreach($_FILES as $id => $name)
{
$this->upload->do_upload('document');
$upload_data = $this->upload->data();
$url = $path2 . $upload_data['file_name'];
$data = array('nom' => $upload_data['raw_name'], 'description' => $_POST['description'], 'url' => $url, 'user_id' => '17');
$this->db->insert('pdf', $data);
}
redirect("/login/docu");
}
So, when I var_dump the $_POST array, I only have the value of "description", and not of "pays" and "magasin".
Can you help me please?
Thanks for your time.
Seems like you are accessing localstorage value , you are posting it somewhere and then submiting the form.
More you are submiting the form which dont have this pays & magasin so i have a trick using which you can achieve it.
Create two hidden inputs inside your HTML form like
<input type="hidden" name="pays" id="pays">
<input type="hidden" name="magasin" id="magasin">
Now before ajax call give them values after getting it from local storage, like this.
user = JSON.parse(sessionStorage.getItem('user'));
pays = localStorage.getItem("pays");
magasin = localStorage.getItem("magasin");
$("#pays").val(pays);
$("#magasin").val(magasin);
$.ajax({ .... });
Continue your code and enjoy.
Hopefully it will work for you.
The issue is because you are not preventing the form from being submit normally, so the AJAX request is cancelled. Instead of using the click event of the button, hook to the submit event of the form and call preventDefault(). Try this:
$('#form_saisie').submit(function(e) {
e.preventDefault();
if ($('#document').val() != "" && $('#description').val() != ""){
api_sendvalue_adddoc();
}
if ($('#document').val() == "")
alert('test');
else if ($('#description').val() == "")
alert('test2');
});
EDIT:
Here is a working example of a ajax post to codeigniter:
View
<script>
$( document ).ready(function () {
// set an on click on the button
$("#button").click(function () {
$.ajax({
type: 'POST',
url: "[page]",
data: {pays: "asd", magasin: "dsa"},
success: function(data){
alert(data);
$("#text").html(data);
console.log(data);
},
error: function(xhr){
alert(xhr.responseText);
console.log(xhr.responseText);
}
});
});
});
</script>
Controller
<?php
// main ajax back end
class Time extends CI_Controller {
// just returns time
public function index()
{
var_dump($_POST);
echo time();
}
}
?>
Output
array(2) {
["pays"]=>
string(3) "asd"
["magasin"]=>
string(3) "dsa"
}
1473087963
Working example here
So you should check the request that you're making from AJAX, on dev console. There you should get the response with the var_dump($_POST).
to debug try to make your controller return only the $_POST data, comment the rest. and same thing on javascript side, test only the ajax post and data received.
I'm using laravel 4.2 and currently I don't how to save a csv file into public\csv\ directory using AJAX. I'm still finding some answers. Maybe someone can help me with this.
Here's my code:
In blade view:
{{Form::open(['route' => 'file_upload', 'files' => true, 'id' => 'upload_form', 'method' => 'POST'])}}
{{Form::file('csv_upload', ['id' => 'uploaded_file', 'accept' => 'text/csv'])}}
{{Form::submit('submit', ['class' => 'btn btn-primary btn-xs', 'id' => 'upload'])}}
{{Form::close()}}
Javascript Ajax:
var ajax_ready = 1
var token = {{Session::get('_token')}}
if($.type(originalOptions.data) === 'string') {
options.data = originalOptions.data+"&_token="+token;
}else if($.type(originalOptions.data) === 'object') {
//Here I got a new error
}else{
options.data = $.param(($.extend(originalOptions.data, {'_token':mmad_token})));
}
options.url = originalOptions.url.slice(0,originalOptions.url.indexOf("?_token="));
if (ajax_ready!=1){
jqXHR.abort();
}
ajax_ready = 0;
});
$('form#upload_form').on('submit', function(e){
e.preventDefault();
var uploadFile = $('#uploaded_file');
var ext = $("input#uploaded_file").val().split(".").pop().toLowerCase();
var file = $('input[name="csv_upload"]').val();
if($.inArray(ext, ["csv"]) === -1) {
alert("Please upload a .csv file!");
return false;
}
var csv = uploadFile[0].files;
var form = new FormData(this);
var csvFile = {lastModifed: csv[0].lastModified, fileName: csv[0].name, size: csv[0].size, fileType: csv[0].type};
$.post('{{ URL::route("file_upload") }}?_token={{Session::token()}}',{
data: form
}).done(function(response){
});
});
PHP:
public function upload_csv()
{
$inputs = Input::all();
$csvFile = $inputs['data']['fileName'];
$path = public_path().DIRECTORY_SEPARATOR.'csv'.DIRECTORY_SEPARATOR;
$path2 = public_path('csv/');
if(is_dir($path2))
{
#move_uploaded_file($csvFile, $path2.$csvFile); //This line can't move the uploaded files in my desired directory
}
return json_encode(['success' => 1, 'description' => 'Successfully Upload File']);
}
This code below does work when not using AJAX:
if(Input::hasFile('csv_upload'))
{
$file = Input::file('csv_upload');
$originalFilename = $file->getClientOriginalName();
$rules = ['csv_upload' => 'required|file:csv'];
$validate = Validator::make(['csv_upload' => $file], $rules);
if($validate->fails())
{
return json_encode(['error' => 1, 'description' => 'File must be in .csv format']);
}
$path = public_path('/csv/');
if(!file_exists($path))
{
mkdir($path);
}
}
Console.log of csv
You can not move file because when you submit form with ajax file is not being sent with ajax,For sending file you have to send file with FormData() javascript Object.
If you check in upload_csv controller by putting print_r($_FILES); you will get empty array.
So use FormData on client side for appending file, then try agian.
You aren't getting error beacuse you have used php Error Control Operators likes#move_uploaded_file($csvFile, $path2.$csvFile);.
if you need working example then tell me i will give it to you.
Code For Your Help:
1. In blade view:
<script type="text/javascript">
$('form#upload_form').on('submit', function(e){
e.preventDefault();
var uploadFile = $('#uploaded_file');
var ext = $("input#uploaded_file").val().split(".").pop().toLowerCase();
var file = $('input[name="mmad_csv_upload"]').val();
if($.inArray(ext, ["csv"]) === -1) {
alert("Please upload a .csv file!");
return false;
}
var csv = uploadFile[0].files;
var formData = new FormData($(this)[0]);
formData.append('uploaded_file', $("#uploaded_file")[0].files[0]);
formData.append('lastModifed', csv[0].lastModified);
formData.append('fileName', csv[0].name);
console.log(formData);
$.ajax({
url: '{{ URL::route("file_upload") }}',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function (returndata) { //alert(returndata); return false;
}
});
});
</script>
2.Controller
public function file_upload(Request $request)
{
$inputs = Input::all();
$csvFile = $inputs['fileName'];
$path = public_path().DIRECTORY_SEPARATOR.'csv'.DIRECTORY_SEPARATOR;
$path2 = public_path('/csv/');
if(is_dir($path2))
{
$success = $request->file('uploaded_file')->move($path2, $csvFile);
}
return json_encode(['success' => 1, 'description' => 'Successfully Upload File']);
}
To move the uploaded file to a new location, you should use the move method. This method will move the file from its temporary upload location (as determined by your PHP configuration) to a more permanent destination of your choosing:
Input::file('fileName')->move($destinationPath, $fileName);
If you need additional validations, you can check it at http://laravel.com/docs/5.1/requests#files
Default AJAX POST does not support file uploads. Use jQuery Form to upload files successfully. Full documentation of file upload at http://malsup.com/jquery/form/#file-upload
Below my example of a recentlty build script... My Controller uploads the files to S3, but is easy to be implemented with local storage.
var progress = function(event, position, total, percent) {
$(".progress-bar").width(percent + '%');
$(".progress-bar").html(percent + '%');
if(percent > 50) {
$(".progress-bar").css('color','#fff');
}
if(percent == 100) {
setTimeout(function(){
$(".progress").html('<span class="processing-msg">Processing... Please be patient!</span>');
$(".processing-msg").fadeIn('slow');
}, 1000);
}
}
var success = function(data) {
var obj = $.parseJSON(data);
$("#"+obj.hidden, parent.document).val(obj.filename);
var src = 'https://s3.amazonaws.com/spincms'+obj.path+'thumb_'+obj.filename;
$("#uploaded-"+obj.hidden, parent.document).html('<img class="img-circle uploaded-img" src="' + src + '">');
$(".progress").html('<span class="processing-msg-next">File has been uploaded and processed. Do not forget to submit the form!</span>');
}
var options = {
target: '#output',
uploadProgress: progress,
success: success,
resetForm: true
};
$(document).on('click', "#upload-now", function(e) {
$(".progress").html('<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div>');
if($("#upload-form input[type=file]")[0].files.length == 0) {
$(".progress").html('<span class="processing-msg-next">No file selected!</span>');
return false;
} else {
var name = $("#upload-form input[name='name']").val();
var token = $("#upload-form input[name='_token']").val();
var file_name = $("#upload-form input[type=file]")[0].files[0].name;
$("#upload-form").ajaxSubmit(options);
}
}
});
Since you are using jQuery you can use the form plugin as it will make things much more easier for you to work with for example , this is the jquery part that you will use :
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#upload_form').ajaxForm(function() {
alert("Your file has been uploaded, thanks");
});
});
and in your controller you can code it like :
pubilc function postUpload()
{
$success = false;
if(Request::ajax())
{
if(Input::hasFile('csv_upload'))
{
$file = Input::file('csv_upload');
if(!File::isDirectory(storage_path('csv'))) {
File::createDirectory(storage_path('csv'));
}
$file->move(storage_path('csv'), $file->getClientOriginalName());
// now your file is on app/storage/csv folder
$filePath = storage_path('csv/'.$file->getClientOriginalName());
$success = true;
}
}
return Response::json(['success'=>$success]);
}
I want to get value from file input from angularjs form in laravel, but i can't get the value.
why?
angularjs:
<div ng-controller="UploadImgController" >
<div ng-repeat="image in images">
<img ng-src="{{image.image}}" />
</div>
<form ng-submit="uploadImg()" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="path" id="path" ng-model="addimages.path" accept="image/*" app-filereader>
<input type="text" name="propertyid" ng-model="addimages.propertyid">
<input type="submit" value="Upload Image" name="submit" class="btn btn-primary" >
</form>
</div>
laravel (UploadImgController.php):
public function store()
{
$file = Input::file('path');
echo "file: ".$file;
}
(routes.php):
Route::resource('img','UploadImgController');
I got no value. What should I do? Thank you. :)
I recommend using ng-file-upload.
View
<button ng-file-select ng-model="myFiles" ng-file-change="upload($files)">Upload</button>
Angular JS
var app = angular.module('fileUpload', ['angularFileUpload']);
app.controller('MyCtrl', ['$scope', '$upload', function ($scope, $upload) {
$scope.upload = function (files) {
if (files && files.length){
for (var i = files.length - 1; i >= 0; i--) {
var file = files[i];
$upload.upload({
url: '/upload',
fields: {key: 'value'},
file: file
})
.progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('File upload ' + progressPercentage + "% complete.");
})
.success(function (data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
console.log(data);
});
}
}
};
}
]);
Laravel Route
Route::post('upload', [
'uses' => 'FileUploadController#upload'
]);
Laravel Controller
public function upload() {
$file = \Input::file('file');
return $file;
}
You can pull that off without a plugin actually. I did face a similar problem once and this is how I went about it.
View
<input type="file" name="file" onchange="angular.element(this).scope().uploadImage(this.files)"/>
Angularjs Controller
$scope.uploadavtar = function (files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post("/upload-url" + $scope.school.profile.id, fd, {
withCredentials: true,
headers: {'Content-Type': undefined},
transformRequest: angular.identity
}).then(function successCallback(response) {
$scope.result = response;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
console.log(response);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
Routes.php
Route::post('/upload-url', 'UsersController#uploadFile');
Laravel Controller
// Upload files
public function uploadFile(Requests\UpdateuploadfileRequest $request, $id)
{
$extension = Input::file('file')->getClientOriginalExtension();
$fileName = time().'.'.$extension; // renameing image
$destination = 'uploads/img'. $fileName;
move_uploaded_file($_FILES['file']['tmp_name'], $destination);
}
}
Request validation file (UpdateuploadfileRequest.php)
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [
];
return $rules;
}