AngularJS Upload File is not Working - php

I am trying to upload file to read in php. But, I unable to transmit a file over to the php.
My code was,
HTML Code:
<label>Import</label>
<div class="form-group">
<input type="file" ng-file-select="uploadFile($files)" />
</div>
app.js:
var app = angular.module('myApp','ngRoute','myApp.bulk','ngSanitize','angularFileUpload']);
bulk.js
var bulkApp = angular.module('myApp.bulk', ['ngResource','ngRoute','ngSanitize']);
bulkApp.factory('FileUploadService', function ($http) {
var api = {
uploadFile: function (file, callback) {
alert(file.name);
$http.uploadFile({
url: 'xxx/services.php?upload=1',
file: file
}).progress(function(event) {
console.log('percent: ' + parseInt(100.0 * event.loaded / event.total));
}).error(function (data, status, headers, config) {
console.error('Error uploading file')
callback(status);
}).then(function(data, status, headers, config) {
callback(null);
});
}
}
return api;
});
bulkApp.controller('bulkController', function($scope,$rootScope,$filter,FileUploadService) {
var service = FileUploadService;
/**
* Handler to upload a new file to the server.
*/
$scope.uploadFile = function ($files) {
var $file = $files[0];
service.uploadFile($file, function (error) {
if (error) {
alert('There was a problem uploading the file.');
}
// handle successfully-uploaded file
})
}
});
services.php
if(isset($_REQUEST) && isset($_REQUEST['upload']))
{
var_dump($_FILES);
/* read functionality over here */
}
I referred this link
i am getting TypeError: $http.uploadFile is not a function error.
please help. thanks in advance .

use $upload service instead of $http:
bulkApp.factory('FileUploadService', function ($upload) {
var api = {
uploadFile: function (file, callback) {
$upload.upload({
url: 'xxx/services.php?upload=1',
file: file
}).progress(function(event) {
console.log('percent: ' + parseInt(100.0 * event.loaded / event.total));
}).error(function (data, status, headers, config) {
console.error('Error uploading file')
callback(status);
}).then(function(data, status, headers, config) {
callback(null);
});
}
}
return api;
});

Related

Problem with uploading some files using Blueimp upload + cropper.js

I have a system where users can send some photos to the server, and the client receive it to make polaroid versions of them.
The user has the option to crop them or not.
I used Blueimp (https://github.com/blueimp/jQuery-File-Upload) to upload the images and cropper.js (https://fengyuanchen.github.io/cropperjs/) to crop them.
But some users are complaining that some files is not uploading, but no error is shown.
Isn't the extension, isn't the size... I don't know what could be the problem...
In this file (jquery.fileupload-ui.js) I found a line of code that, if I remove it, it works, but I can't see the file's thumbnails. But the file is uploaded. Is the last line before the always function.
add: function (e, data) {
if (e.isDefaultPrevented()) {
return false;
}
var $this = $(this),
that = $this.data('blueimp-fileupload') ||
$this.data('fileupload'),
options = that.options;
data.context = that._renderUpload(data.files)
.data('data', data)
.addClass('processing');
options.filesContainer[
options.prependFiles ? 'prepend' : 'append'
](data.context);
that._forceReflow(data.context);
that._transition(data.context);
data.process(function () {
// return $this.fileupload('process', data);
}).always(function () {
data.context.each(function (index) {
$(this).find('.size').text(
that._formatFileSize(data.files[index].size)
);
}).removeClass('processing');
that._renderPreviews(data);
}).done(function () {
data.context.find('.start').prop('disabled', false);
if ((that._trigger('added', e, data) !== false) &&
(options.autoUpload || data.autoUpload) &&
data.autoUpload !== false) {
data.submit();
}
}).fail(function () {
if (data.files.error) {
data.context.each(function (index) {
var error = data.files[index].error;
if (error) {
$(this).find('.error').text(error);
}
});
}
});

How to fix error when trying to upload file to backend?

I'am trying to upload a file to the server by using a service which passes the file to the php backend.
It works, but only once. If I try to repeat uploading another file (without reloading the page) it does not get send and this error occurs:
ERROR TypeError: "this.fileManagerService.uploadFile is not a function"
playground.component.html
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<input type="file" name="avatar" (change)="onFileSelect($event)" />
<button type="submit">Upload</button>
</form>
playground.component.ts
export class PlaygroundComponent implements OnInit {
form: FormGroup;
fileManagerResponse;
constructor(private formBuilder: FormBuilder, private fileManagerService: FileManagerService) { }
ngOnInit() {
this.form = this.formBuilder.group({
avatar: ['']
});
}
onFileSelect(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.form.get('avatar').setValue(file);
}
}
onSubmit() {
const formData = new FormData();
formData.append('avatar', this.form.get('avatar').value);
this.fileManagerService.uploadFile(formData).subscribe(
(res) => {
this.fileManagerService = res;
console.log(res);
},
(err) => {
console.log(err);
}
);
}
}
FileManagerService.ts
export class FileManagerService {
SERVER_URL: string = "http://127.0.0.1/backend/api/";
constructor(private httpClient: HttpClient) { }
public uploadFile(data) {
let uploadURL = `${this.SERVER_URL}/filemanager/upload.php`;
return this.httpClient.post<any>(uploadURL, data);
}
}
The error occurred in below line.
this.fileManagerService = res;
You cannot assign res to the instance of the FileManagerService.
Remove it. Everything will be fine.

How to send a file via Axios to Laravel

I need to post a File from client to server via Axios.
Here is my Vuejs code :
methods: {
'successUpload': function (file) {
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
axios.post('/Upload/File',file, config).then(function (response) {
console.log(response.data);
});
}
}
And here is my Laravel code for handling sent file :
public function uploadFile(Request $request)
{
if($request->hasFile('file'))
return "It's a File";
return "No! It's not a File";
}
But it always returns No It's not a File.
Any helps would be great appreciated.
You have to create a FormData object and append the image file.
methods: {
'successUpload': function (file) {
let data = new FormData();
data.append('file', document.getElementById('file').files[0]);
axios.post('/Upload/File',data).then(function (response) {
console.log(response.data);
});
}
}
An example is here.
Let me know if that works.

Angular/PHP: upload file data in $_POST, not $_FILES

I'm using AngularJS v1.6.1, Apache 2.4.10 on Debian with PHP 5.6.24 and I'm trying to upload a file to my server using $http POST service.
On my php.ini, max file size is set to 8Mo, max post size too, upload file is on, and memory size limit is set to 128Mo.
Form:
<input type="file" accept="application/pdf" id="uploadOT" max-files="1" ng-model="uploadOT" name="uploadOT" valid-file required ng-class="{'md-input-invalid':uploadForm.uploadOT.$error.validFile}" />
Angular directive: (when input content change, get a FileReader object and send file)
myModule.directive('validFile', function() {
return {
require: 'ngModel',
link: function(scope, elt, attrs, ctrl) {
ctrl.$setValidity('validFile', elt.val() !== '');
elt.bind('change', function() {
var file = document.getElementById('uploadOT').files;
var reader = new FileReader();
reader.onload = function(e) {
scope.sendFile(reader, scope.id);
};
scope.showUploadProgress = true;
scope.filename = file[0].name;
reader.readAsBinaryString(file[0]);
ctrl.$setValidity('validFile', elt.val() !== '');
scope.$apply(function() {
ctrl.$setViewValue(elt.val());
ctrl.$render();
});
});
}
};
});
Inside controller:
$scope.sendFile = function(reader, id) {
var fd = new FormData();
fd.append('id', id);
fd.append('file', reader.result);
fd.append('MAX_FILE_SIZE', 8 * 1024 * 1024);
$http.post('api/upload.php', fd, {
headers: {'Content-Type' : undefined },
transformRequest: angular.identity
}).then(function() {
alert('upload success');
}, function() {
$scope.showUploadError = true;
$scope.showUploadProgress = false;
$scope.postError = 'Une erreur inconnue est survenue !';
});
};
On server side (file api/upload.php), I print variables $_POST and $_FILES with print_r().
Why is $_FILES always empty, and my file data is in $_POST['file']?
I can create file from $_POST['file'] data with php function file_put_contents() but I cannot make verifications that I can make with $_FILES. Is it really important (security issues)?
If I change my POST Content-Type to multipart/form-data, the same thing happend.
I presume it's because you forgot to specify the encoding type of your form element.
enctype="multipart/form-data"
So, by default - the browser will assume that the form encoding type is "application/x-www-form-urlencoded" which does not support files in this way. You can still securely send file binary data with the stock encoding method however, this might be where performance and functionality are determining factors to which you choose. I recommend running some tests to confirm which is the fastest. In some cases, the difference will be negligible and will likely be for sake of consistency.
Skip the FileReader API and use the file object directly:
<input type=file files-input ng-model="files" ng-change="upload()" />
The filesInput Directive
angular.module("myApp").directive("filesInput", function() {
return {
require: 'ngModel',
link: function linkFn (scope, elem, attrs, ngModel) {
elem.on("change", function (e) {
ngModel.$setViewValue(elem[0].files, "change");
});
},
};
});
The upload() function
vm.upload = function() {
//var formData = new $window.FormData();
//formData.append("file-0", vm.files[0]);
var config = { headers: { "Content-Type": undefined } };
$http.post(url, vm.files[0], config)
.then(function(response) {
vm.result = "SUCCESS";
}).catch(function(response) {
vm.result = "ERROR "+response.status;
});
};
The XHR API send() method can post either a file object or a FormData object. It is more efficient to send the file object directly as the XHR API uses base64 encoding for the FormData object which has a 33% overhead.
The DEMO on PLNKR.
To make it works, I had to do these modifications:
Directive:
myModule.directive('validFile', function() {
return {
require: 'ngModel',
link: function(scope, elt, attrs, ctrl) {
ctrl.$setValidity('validFile', elt.val() !== '');
elt.bind('change', function() {
var file = document.getElementById('uploadOT').files;
var reader = new FileReader();
reader.onload = function(e) {
scope.sendFile(file[0], scope.OT); ////CHANGE HERE
};
scope.showUploadProgress = true;
scope.filename = file[0].name;
reader.readAsArrayBuffer(file[0]); ////CHANGE HERE
ctrl.$setValidity('validFile', elt.val() !== '');
scope.$apply(function() {
ctrl.$setViewValue(elt.val());
ctrl.$render();
});
});
}
};
});
Inside Controller
$scope.sendFile = function(file, id) {
var fd = new FormData();
fd.append('id', id);
fd.append('file', file);
fd.append('MAX_FILE_SIZE', 8 * 1024 * 1024);
$http({
method: 'POST',
url: 'upload.php',
data: fd,
headers: {'Content-Type': undefined, 'Process-Data': false},
transformRequest: angular.identity
}).then( function() {
console.log('success');
}, function() {
console.log('failure');
});
};

Get File Input Value in Laravel Via AngularJS form

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

Categories