I have to create a quiz system for the website. I have to upload image type question and also image type options on single page using angularjs and webapi. I want to check in api that which image is for option and which image is for question image while array of image is with name visible I can show images in array here is my code:
app.directive('uploadFiles', function () {
return {
scope: true, //create a new scope
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var files = event.target.files;
console.info(files);
for (var i = 0; i < files.length; i++) {
scope.$emit("seletedFile", { file: files[i] });
}
});
}
};
});
app.controller('questionairController', function ($scope, $http) {
$scope.files = [];
$scope.$on("seletedFile", function (event, args) {
$scope.fileList = true;
$scope.$apply(function () {
$scope.files.push(args.file);
});
});
$scope.addQuestionair = function () {
var cID = document.getElementById("CustomerID").value;
var pID = document.getElementById("ProjectID").value;
$scope.question.CustomerID = cID;
$scope.question.ProjectID = pID;
console.info($scope.question);
console.info($scope.OptionsList);
var viewObj = {
questionair: $scope.question,
options: $scope.OptionsList
};
console.info(viewObj);
$http({
method: 'POST',
url: 'api/Questions/AddQuestion',
headers: { 'Content-Type': undefined },
uploadEventHandlers: {
progress: function (e) {
if (e.lengthComputable) {
var progressValue = (e.loaded / e.total) * 100;
$scope.ProgressWidth = 0;
$scope.ProgressWidth = { 'width': progressValue + '%' };
}
}
},
transformRequest: function (data) {
console.info("in transform");
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
for (var i = 0; i < data.files.length; i++) {
formData.append(data.files[i].name, data.files[i]);
}
return formData;
},
data: { model: viewObj, files: $scope.files }
}).then(function (response) {
console.info(response);
$scope.SaveMessage = response.data;
GetQuestionair();
$scope.question = null;
}, function (error) {
});
};
Here is my API function
[HttpPost]
public HttpResponseMessage AddQuestion()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
HttpFileCollection hfc = HttpContext.Current.Request.Files;
var model = HttpContext.Current.Request["model"];
ViewModel viewModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ViewModel>(model);
if (viewModel == null)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
var root = HttpContext.Current.Server.MapPath("~/SiteImages/");
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
HttpPostedFile hpf = hfc[0];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(root + "/" + Path.GetFileName(hpf.FileName));
}
{
db.Tbl_Questionair.Add(viewModel.questionair);
db.SaveChanges();
foreach (var item in viewModel.options)
{
item.CreatedOn = DateTime.Now;
item.QID = viewModel.questionair.ID;
item.CustomerID = viewModel.questionair.CustomerID;
item.ProjectID = viewModel.questionair.ProjectID;
db.Options.Add(item);
db.SaveChanges();
}
return Request.CreateResponse(HttpStatusCode.OK, "Data successfully saved!");
}
}
I am trying to pick a file and upload it to FTP.
For now I get the a 415 (media type unsupported) error when consuming springboot service in angularjs when sending the image.
This is my angular controller:
Controllers.controller('UploadCtrl', [ '$scope', '$http',
function($scope, $http) {
$scope.doUploadFile = function() {
var file = $scope.uploadedFile;
var url = "/ui/upload";
var data = new FormData();
data.append('uploadfile', file);
var config = {
transformRequest : angular.identity,
transformResponse : angular.identity,
headers : {
'Content-Type' : undefined
}
}
$http.post(url, data, config).then(function(response) {
$scope.uploadResult = response.data;
}, function(response) {
$scope.uploadResult = response.data;
});
};
} ]);
My Service Controller JAVA:
#POST
#Path("/upload")
#Consumes("multipart/form-data")
public String upload(#RequestParam("uploadfile") MultipartFile file) throws Exception {
try {
return "You successfully uploaded - " + file.getOriginalFilename();
} catch (Exception e) {
throw new Exception("FAIL! Maybe You had uploaded the file before or the file's size > 500KB");
}
}
For now just getting the file name. What am 'I doing wrong when consuming the POST ?
Thank you in advance
try this:-
HTML
<img ng-src="{{profilePicturePath}}" class="img-responsive"
alt="Image Not found" style="height:150px; width: 150px;">
<input type="file" class="form-control" style="display: none;"
file-model="profileFile" multiple name="profileFile"
id="profileFile" accept="image/*"/>
JS
$scope.profileFile = null;
$scope.$watch('profileFile', function (profileFile) {
if (profileFile && profileFile.name) {
if (profileFile.size / 1012 < 512) {
if (profileFile.type.startsWith("image/")) {
uploadProfilePicture(profileFile);
}
}
}
});
function uploadProfilePicture(profileFile) {
aspirantService.uploadProfilePicture(profileFile).then(function (response) {
getProfilePicturePath();
});
}
this.uploadProfilePicture = function (file) {
var fd = new FormData();
fd.append("doc", file);
return $http.post(Server.url + 'aspirant/pic/', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
};
and JAVA
#Path("pic")
#POST
#Consumes(MediaType.WILDCARD)
public Response uploadProfilePicture(MultipartFormDataInput input, #Context UserSession session) {
for (Map.Entry<String, List<InputPart>> entry : input.getFormDataMap().entrySet()) {
List<InputPart> list = entry.getValue();
for (Iterator<InputPart> it = list.iterator(); it.hasNext();) {
InputPart inputPart = it.next();
try {
MultivaluedMap<String, String> header = inputPart.getHeaders();
String fileName = RequestHeaderInfo.getFileName(header);
String contentType = RequestHeaderInfo.getContentType(header);
InputStream inputStream = inputPart.getBody(InputStream.class, null);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
//here code for write file
return Response.ok(proxy).build();
} catch (Exception ex) {
logger.log(Level.SEVERE, "Error while getting document!", ex);
}
}
}
return Response.ok().build();
}
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;
}
use $cordovaFileTransfer to upload images,but it stop at 99%, $_FILES is empty in PHP;
and i get evt object.
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"16656","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"33040","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"98576","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"131344","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"147728","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"164112","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"180496","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"213264","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"229648","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"65808","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"82192","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"114960","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"295184","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"262416","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"311568","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"327952","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"344336","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"360720","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"377104","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"409872","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"442640","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"393488","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"426256","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"459024","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"475408","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"491163","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"196880","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"246032","total":"491176"}
what's wrong with the property loaded;why it increase repeatly;
upload code
$scope.upload = function(imageURI) {
$scope.dangerList[$scope.setting.num][$scope.setting.imageType + '1pic'] = imageURI;
var server = 'http://localhost/test.php';
var dirName = 'check';
var desName = 'test';
var options = {
'httpMethod': 'POST',
'params': {
'dirName': dirName,
'desName': desName
}
};
var promise = $cordovaFileTransfer.upload(server, imageURI, options, true);
promise.then(function(data) {
console.log(data);
}, function(data) {}, function(evt) {
$ionicLoading.show({
template: '<p>upload:' + parseInt(100.0 * evt.loaded / evt.total) + '%</p>',
//duration: 1000,
});
});
return promise;
};
and ngCordova\src\plugins\fileTransfer.js
angular.module('ngCordova.plugins.fileTransfer', [])
.factory('$cordovaFileTransfer', ['$q', '$timeout', function($q, $timeout) {
return {
download: function(source, filePath, options, trustAllHosts) {
var q = $q.defer();
var ft = new FileTransfer();
var uri = (options && options.encodeURI === false) ? source : encodeURI(source);
if (options && options.timeout !== undefined && options.timeout !== null) {
$timeout(function() {
ft.abort();
}, options.timeout);
options.timeout = null;
}
ft.onprogress = function(progress) {
q.notify(progress);
};
q.promise.abort = function() {
ft.abort();
};
ft.download(uri, filePath, q.resolve, q.reject, trustAllHosts, options);
return q.promise;
},
upload: function(server, filePath, options, trustAllHosts) {
var q = $q.defer();
var ft = new FileTransfer();
var uri = (options && options.encodeURI === false) ? server : encodeURI(server);
if (options && options.timeout !== undefined && options.timeout !== null) {
$timeout(function() {
ft.abort();
}, options.timeout);
options.timeout = null;
}
ft.onprogress = function(progress) {
q.notify(progress);
};
q.promise.abort = function() {
ft.abort();
};
ft.upload(filePath, uri, q.resolve, q.reject, options, trustAllHosts);
return q.promise;
}
};
}]);
and push interceptor
.factory('UserInterceptor', function ($q, $rootScope) {
return {
request:function(config){
config.headers = config.headers || {};
config.headers.UID = $rootScope.user.id || 0;
return config;
},
requestError: function(err){
return $q.reject(err);
},
response: function (response) {
return response;
},
};
})
it could work few days ago.
during the time,
add plaform with android#5.1.1 instead of android#4.1.1;
update cordova;
use ionic 1.7.3 now;
and here is the download code,it can works,but will download file twice
$scope.down = function(fname) {
var fileTransfer = new FileTransfer();
var uri = encodeURI($rootScope.rootUrl + fname);
var fileURL = cordova.file.externalRootDirectory + fname;
fileTransfer.download(
uri,
fileURL,
function(entry) {
console.log(entry);
},
function(error) {
console.log(error);
},
false, {
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
};
This is actually the response from progress event of cordovaFileTransfer.
On success it'll give response something like this:
Object {bytesSent: 3228135, responseCode: 200, response: "<!-- Served from 80.251.0.59 / test.talia.net, as …imited↵</p>↵↵</td></tr></table>↵↵</body>↵</html>↵", objectId: ""}
But as per the output you are getting,I think the function is getting interrupted by the same method from another instance because your whole file was almost uploaded in the 3rd last line.
"cancelable":"false","lengthComputable":"true","loaded":"491163","total":"491176"}
And then it picked up from some another point.
Please provide the code so I can try to assist you further.
Thank you
I am trying to understand Angular's promises and scopes. Actually I implemented the directive bellow. The thing that I want to do is to receive images from server and store locally in order to cache them for next times. Also I want to show a spinner before the load of image is completed and show it after the completion.
How can update variable newUrl into directive when completed all of these promises?
Do you have any idea?
My HTML code is:
<div style="text-align: center;"
cache-src
url="https://upload.wikimedia.org/wikipedia/commons/c/c0/Aix_galericulata_(Male),_Richmond_Park,_UK_-_May_2013.jpg">
</div>
My directive is:
.directive('cacheSrc', [function () {
return {
restrict: 'A',
scope: {
url: '#'
},
controller: 'cacheSrcCtrl',
template: '<img width="100%" ng-if="newUrl!=null" src="{{newUrl}}"><ion-spinner ng-if="newUrl==null" icon="spiral"></ion-spinner>',
};
}])
And the controller of directive has the function bellow:
document.addEventListener('deviceready', function () {
$scope.updateUrl = function (newUrl) {
$scope.newUrl = newUrl;
};
var tmp = $scope.url;
$cordovaSQLite.execute(db, 'SELECT * FROM images where url = (?)', [tmp])
.then(function (result) {
if (result.rows.length > 0) {
$scope.exists = true;
for (var i = 0; i < res.rows.length; i++) {
var image = {
id: res.rows.item(i).id,
url: res.rows.item(i).url,
uri: res.rows.item(i).uri
};
$scope.updateUrl(image.uri);
}
} else {
$scope.exists = false;
var fileTransfer = new FileTransfer();
var uri = encodeURI(tmp);
var uriSave = '';
var fileURL = cordova.file.dataDirectory + uri;//'kaloudiaImages';// + getUUID();// + "DCIM/myFile";
fileTransfer.download(
uri, fileURL, function (entry) {
uriSave = entry.toURL();
KaloudiaDB.add(tmp, fileURL);
$scope.newUrl = fileURL;
$scope.updateUrl(fileURL);
},
function (error) {
console.log("download error code" + error.code);
},
false, {
headers: {
// "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
).then(function (data) {
$scope.newUrl = fileURL;
});
}
}, function (error) {
$scope.statusMessage = "Error on saving: " + error.message;
})
.then(function (data) {
$scope.$apply(function () {
$scope.newUrl = fileURL;
});
});
});