File upload in angularjs with code igniter - angularjs

What I am trying to do is to upload excel file using angular and codeigniter .
But the problem is when I am am uploading it is not been accepted by the CI function ,Status code is 200 when I am sending but I am getting empty array when I am printing
print_r($_POST); print_r($_FILES);
Here is my service:
function UploadExcel(file,uploadUrl) {
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': 'multipart/form-data'},
})
.success(function(){
})
.error(function(){
});
Here is my directive
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
Here is my Controller
$scope.ImportApplicant = function() {
var file = $scope.myFile;
var uploadUrl = 'user/fileUpload';
UserService.UploadExcel(file, uploadUrl);
}

For angular code
$scope.setFile1 = function(element)
{
$scope.currentFile = element.files[0];
var t = element.files[0].name;
var vali = t.split('.');
var length = vali.length-1;
var final = vali[length];
if(final=='txt' || final=='pdf' || final=='doc' || final=='docs')
{
var reader = new FileReader();
reader.onload = function(event)
{
$scope.missing.image = event.target.result
$scope.$apply();
$("#image_show").show();
}
reader.readAsDataURL(element.files[0]);
}
}
Codeigniter
$base64_string=$data['profile_image'];
if (preg_match('/base64/i', $base64_string))
{
$randomfile=time().'.jpeg';
$filename='./uploads/users/'.$randomfile;
$this->Cashback_model->base64_to_jpeg($base64_string, $filename);
}
else {
$file_name = explode('/', $base64_string);
foreach ($file_name as $keyval) {
$randomfile = $keyval;
}
}
model
public function base64_to_jpeg($base64_string,$output_file) {
$ifp = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
return $output_file;
}

Related

sending files via POST with AngularJS

I have a problem sending data via POST in angular,
my data include 2 files and some text field,
the problem is that the service doesn't receives any data.
this is my code:
var inputs = document.querySelectorAll( 'input[type="file"]' );
Array.prototype.forEach.call( inputs, function( input ){
input.addEventListener( 'change', function( e ){
if(this.id == "zipToUpload")
$scope.zipToUpload = this.files[0];
else
$scope.imgToUpload = this.files[1];
});
});
$scope.submit = function(){
var getInput = {nome: $scope.app_name, zipToUpload: $scope.zipToUpload, imgToUpload: $scope.imgToUpload, url: $scope.app_url,
secure: $scope.checkbox_pass, hide: $scope.checkbox_hide, beta: $scope.checkbox_beta, password: $scope.app_pass, location: "1" };
var req = {
method: 'POST',
url: 'api/rest/app/insert_app.php',
headers: {
'Content-Type': undefined
},
data: getInput
}
$http(req)
.then(function(result) {
console.log(result);
});
}
You can not directly upload file using model in angular. First you need a directive to bind files to the model.
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
And the input will be like :
<input type = "file" file-model = "myFile"/>
And the you can send post request using form data
$scope.upload = funtion(){
var fd = new FormData();
fd.append('file', $scope.myFile);
var req = {
method: 'POST',
url: 'api/rest/app/insert_app.php',
headers: {
'Content-Type': undefined
},
data: fd
}
$http(req)
.then(function(result) {
console.log(result);
});
}

Connection terminated parsing multipart data in Angulrjs and JAX-RS

I wish to send my localhost (in spring boot server) a selected image from the user using AngularJS and add data object in BD using JAX-RS.
-Code HTML:
<form role="form" enctype="multipart/form-data" name="myForm" ng-submit="uploadfile()">
<label class="control-label">Image:</label>
<input type="file" class="form-control " file-model="Image" >
<input type="text" class="form-control " ng-model="name" >
<input type="text" class="form-control " ng-model="lastname" >
<button type="submit"> save</button>
</form>
--code AngularJS;
var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
app.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
//fd.append('file', file);
angular.forEach(file, function(file) {
fd.append('file', file);
});
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(response) {
console.log("done post "+response);
}).catch(function(e) {
console.log('failed to post: ', e);
throw e;
})
}
}]);
//upload file and data object of user
$scope.uploadfile = function() {
var file = $scope.Image;
console.dir(file);
var uploadUrl ="http://localhost:8000/auditconfig/images/"+file.name;
fileUpload.uploadFileToUrl(file, uploadUrl); // error here "failed to post"
var user = {
name: $scope.name,
lastname: $scope.lastname,
image:file.name
};
$http.post(url+"/add", user) //The user is added to the database
.success(function(data) {
$scope.ListUsers = data;
}).error(function(err, data) {
console.log("error: " +data);
});
};
-After a test of the "uploadfile ()", I get the following results:
//**console.dir(file);
*File:
lastModified:1490260924299
lastModifiedDate; Thu Mar 23 2017 10:22:04 GMT+0100 (Paris, Madrid)
name:"01.png"
size:1637
type:"image/png"
webkitRelativePath:""
__proto__:File
-Test of upload file:
//**console.log('failed to post: ', e);
Failed to load resource: the server responded with a status of 500 (Internal Server Error) :8099/AuditConf/images/01.png
failed to post: Object
Config:Objectd
ata:FormData
__proto__:FormData
headers:Object
Accept:"application/json, text/plain, */*"
Content-Type:undefined
__proto__:Object
method:"POST"
transformRequest:function identity($)
transformResponse:Array(1)
url:"http://localhost:8099/AuditConf/images/Exception--JAX-RS.png"
__proto__:Object
data:Object
error:"Internal Server Error"
exception:"java.lang.RuntimeException"
message:"java.io.IOException: UT000036: Connection terminated parsing multipart data"
path:"/auditconfig/images/Exception--JAX-RS.png"
status:500
timestamp:1490778930961
__proto__:Object
headers:function (name)
status:500 statusText
:"Internal Server Error"
__proto__;Object
The solution is:
var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
this.uploadFileToUrl = function(file, uploadUrl){
var data = new FormData();
data.append('file', file);
return $http.post(uploadUrl, data, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).then(function (results) {
return results;
});
}
//upload file and data object of user
$scope.uploadfile = function() {
var file = $scope.Image;
console.dir(file);
//URL of API not path of floder
var uploadUrl ="http://localhost:8000/auditconfig/UpFile";
fileUpload.uploadFileToUrl(file, uploadUrl);
var user = {
name: $scope.name,
lastname: $scope.lastname,
image:file.name
};
$http.post(url+"/add", user)
.success(function(data) {
$scope.ListUsers = data;
}).error(function(err, data) {
console.log("error: " +data);
});
};
Try this:
this.uploadFileToUrl = function(file, uploadUrl){
var data = new FormData();
data.append('file', file);
//Comment below
//angular.forEach(file, function(file) {
// fd.append('file', file);
//});
return $http.post(uploadUrl, data, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).then(function (results) {
return results;
});
}
See the answers here which accepts multiple files within one object 'file'.

Error 404: Please upload an image - AngularJs

I am trying to upload files in Angular Js. I am following the below example https://plnkr.co/edit/CqIixHWefjYmDfmJPbNF?p=preview provided by #georgeawg in Pass file reader data to service in Angular Js
In index.cshtml
<input type="file" my-files="files" />
<input type="button" name="imageUploadButton" ng-click="uploadFiles()" value="Upload" />
In controller.js
angular.module('testApp.controllers', []).
controller('testApp.Controller', function ($scope, testAPIService, Excel, $timeout, $window, $location, $anchorScroll, $http, sharedDataService) {
var url = "https://siteUrl/UploadImage/";
var config = {
headers: {
"Content-Type": undefined,
}
};
$scope.uploadFiles = function () {
var file = sharedDataService.shared.files[0];
testAPIService.postUploadImage(file).success(function (response) {
alert(respone)
}); };
});
angular.module("testApp.Controller").directive("myFiles", function ($parse, sharedDataService) {
return function linkFn(scope, elem, attrs) {
elem.on("change", function (e) {
alert("hi");
scope.$eval(attrs.myFiles + "=$files", { $files: e.target.files });
scope.$apply();
sharedDataService.shared = scope;
});
};
});
angular.module("testApp.Controller").directive("xdHref", function () {
return function linkFn(scope, elem, attrs) {
scope.$watch(attrs.xdHref, function (newVal) {
newVal && elem.attr("href", newVal);
});
};
});
//In service.js
testAPIService.postUploadImage = function (file) {
var config = {
headers: {
"Content-Type": undefined,
}
};
var url = urlBase + 'UploadImage';
$http.post(url, file, config).
then(function (response) {
alert(response.data.data);
}).catch(function (response) {
alert( "ERROR " + response.status);
});
In the C# API code:
[HttpPost]
[Route("tests/UploadImage")]
public async Task<HttpResponseMessage> UploadImage()
{
Dictionary<string, object> dict = new Dictionary<string, object>();
try
{
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
var postedFile = httpRequest.Files[file];
if (postedFile != null && postedFile.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB
IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png", "jpeg" };
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
var filenameOrigin = postedFile.FileName.Substring(0, postedFile.FileName.LastIndexOf('.'));
var extension = ext.ToLower();
if (!AllowedFileExtensions.Contains(extension))
{
var message = string.Format("Please Upload image of type .jpg,.gif,.png,.jpeg.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else if (postedFile.ContentLength > MaxContentLength)
{
var message = string.Format("Please Upload a file upto 2 mb.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else
{
string filename = String.Format(#"{0}_{1}_{2}{3}", filenameOrigin, Guid.NewGuid(), DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss"), extension);
var filePath = HostingEnvironment.MapPath("~/Images/" + filename);
postedFile.SaveAs(filePath);
if (!String.IsNullOrEmpty(filePath))
{
dict.Add("filePath", filePath);
}
}
}
var messageSuccess = string.Format("Image Updated Successfully.");
dict.Add("Success", messageSuccess);
return Request.CreateResponse(HttpStatusCode.Created, dict);
}
var res = string.Format("Please Upload a image.");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
catch (Exception ex)
{
var res = string.Format("something went wrong");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
}
In var file, I am getting the uploaded file name, size, image type. In the next line, $http.post, the call is moved to catch, and I am getting error :404 - Please upload a image
What is missed? How to fix this?
Thanks

Send some additional parameters with FormData in angularjs

Im trying to find a way to upload some parameters along with a file using FormData but not sure where to look for it on the backend.
HTML:
<input type="file" file-model="myFile"/>
<button class="btn" ng-click="uploadFile()">upload</button>
Directive:
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}])
Controller:
var file = $scope.aFile;
var foo = 'bar';
var fd = new FormData();
fd.append('file', file);
fd.append('foo', foo);
$http.post(api, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(res){
console.log(res.data);
});
Backend:
$_POST = json_decode(file_get_contents('php://input'),true);
$result = saveFile('./img/', 'a_test_file'); /* SUCCEEDS! */
$res = array($_POST, $_FILES, $result); /* $_POST empty, $_FILES ok, $result success */
/* where is foo?? */
Not sure what Im missing or where to look for the additional parameter?

File upload in angularjs mvc

Please see the following code and let me know how can i upload the file in a folder of my project..
where can i write the url? I select the file and it does not get save simply by clicking on the update button.
Thanks in Advance
Ria
var DocTrack = angular.module('DocTrack', []);
DocTrack.controller('DocumentController', DocumentController);
DocTrack.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
DocTrack.service('fileUpload', ['$http', function ($http) {
debugger;
this.uploadFileToUrl = function (file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function () {
alert('File Uploaded Successfully...');
})
.error(function () {
alert('File has not been uploaded');
});
}
}]);
DocTrack.controller('DocumentController', ['$scope', 'fileUpload', function ($scope, fileUpload) {
$scope.uploadFile = function () {
debugger;
var file = $scope.myFile;
console.log('file is ' + JSON.stringify(file));
var uploadUrl = "http://localhost:40966/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
<div ng-controller = "DocumentController">
<input type="file" file-model="myFile" />
<button ng-click="uploadFile()" data-url="">upload me</button>
</div>
var uploadUrl = "http://localhost:40966/fileUpload";
Can you check your backend url it must be same as you specify and during saving your image you must specify your path to store image in backend.
In html form
<div class="form-group col-xs-12 ">
<label class="form-group">Select file</label>
<div class="controls">
<input type="file" file-model="fileUrl"/>
</div>
</div>
in Controller.js you put following code
var file = $scope.fileUrl;
var uploadUrl = "/Uploadfile";
var data = fileUpload.uploadFileToUrl(file, uploadUrl,formdata);
};
In your service
.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl,formdata){
var fd = new FormData();
fd.append('file', file);
fd.append('formdata',angular.toJson(formdata));
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(data){
console.log(data);
return data;
})
.error(function(){
});
}
}]);
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}])
"/Uploadfile" is your backend url

Resources