I wanted to upload an image after the selection without submit button.
I used danialfarids plugins from GitHub.
I suppose he made the server with C#
, which I wanted to change to php
. I'm having problems writing the php file handler.
This is my script files.
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadPic = function(file) {
file.upload = Upload.upload({
method:'POST',
url: 'http://localhost/angular/upload.php',
data: {file: file, username: $scope.username}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}]);
And this is my html file
<form name="myForm" >
<fieldset>
<legend>Upload on file select</legend>
<br>Photo:
<input type="file" ngf-select="uploadPic(picFile)" ng-model="picFile" name="picFile"
accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFiles">
<img ng-show="myForm.file.$valid" ngf-thumbnail="picFile" class="thumb">
<br>
<button ng-disabled="!myForm.$valid"
ng-click="uploadPic(picFile)">Submit</button>
<div class="con">
<div class="pg" style="width:{{picFile.progress}}%" ></p></div>
</div>
<p ng-bind="picFile.progress + '%'"></p>
<span ng-show="picFile.result">Upload Successful</span>
<span class="err" ng-show="errorMsg">{{errorMsg}}</span>
</fieldset>
</form>
This is the css
<style>
.thumb {
width: 240px;
height: 240px;
float: none;
position: relative;
top: 7px;
}
form .progress {
line-height: 1px;
}
.progress {
display: inline-block;
width: 300px;
}
.con{
width:300px;
}
.pg {
font-size: smaller;
background: #000000;
width:0px;
height:1px;
}
</style>
And this is the rudimentary upload.php
(found in localhost/angular/) and I don't think it works.
<?php if ( !empty( $_FILES ) ) {
$tempPath = $_FILES[ 'picFile' ][ 'tmp_name' ];
$uploadPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES[ 'picFile' ][ 'name' ];
move_uploaded_file( $tempPath, $uploadPath );
$answer = array( 'answer' => 'File transfer completed' );
$json = json_encode( $answer );
echo $json; } else {
echo 'No files'; } ?>
My xampp
server is working. And I also included angular files, angularjs
, ng-file-upload-shim.min.js
and ng-file-upload.min.js
from danialfarid.
I Found the answer to this question, the problem was not on the code, the problem happened because I was making XMLHttpRequest to a different domain than I was in. And the easy way to solve this problem is by adding extension to chrome. Cors extension. This solved the problem.