I want to get the image path after the execution of the uploadFiles function. This way, I will have the value assigned to self.ProjectImagePath. But it is not working, I think it executes right after the function call. Anyone can help ?
self.submitProject = function(file) {
console.log("Submit Project \n");
uploadFiles.apply(this, arguments);
console.log(self.ProjectImagePath); ///ERROR HERE!!!! (UNDEFINED)
var data = JSON.stringify({
name: self.ProjectName,
room: self.room,
managers: self.Managers,
members: self.ProjectMembers,
image: self.ProjectImagePath
});
//console.log(data);
$http.post('/rooms/' + self.room + '/project', data).success(function(data) {
//$window.location.href = "/";
});
}
function uploadFiles(file) {
file.upload = Upload.upload({
url: 'projectImages/upload',
data: {
file: file
}
});
file.upload.then(function(response) {
$timeout(function() {
file.result = response.data;
self.ProjectImagePath = file.result;
});
}, function(response) {
if (response.status > 0)
self.errorMsg = response.status + ': ' + response.data;
});
}
After execution, the image is uploaded to the server but I cant get its path.
Im using AngularJS
You were having issues with calling code before the promise (asynchronous action) was finished.
This should do what you need:
self.submitProject = function(file) {
console.log("Submit Project");
function handleSuccess(response) {
self.ProjectImagePath = file.result = response.data;
// Should work correctly.
console.log(self.ProjectImage);
var data = JSON.stringify({
name: self.ProjectName,
room: self.room,
managers: self.Managers,
members: self.ProjectMembers,
image: self.ProjectImagePath
});
$http.post('/rooms/' + self.room + '/project', data).success(function(data) {
//$window.location.href = "/";
});
}
function handleError(response) {
if (response.status > 0)
self.errorMsg = response.status + ': ' + response.data;
}
uploadFiles(file, handleSuccess, handleError);
};
function uploadFiles(file, successCallback, errorCallback) {
file.upload = Upload.upload({
url: 'projectImages/upload',
data: {
file: file
}
});
file.upload.then(successCallback, errorCallback);
}
Related
Trying to upload file from web application to SharePoint directory. Upon successful upload, only the filename is saved to the database. A SharePoint link is hard coded in the frontend to view the file uploaded.
Problem encountered: Sometimes the upload fails with an error message "session was expired.. Please clear the local storage." Clearing cache does not help.
importFiles: retrieves an array of all files from the database.
saveFile: adds the last successfully file name to the end of the array
clearCache: clears the input type [rename field]
var savingFile = function () {
importFiles(() => saveFile(() => clearCache(() => {
$('#modal').modal('hide');
init();
})));
Following is to upload the selected file to the SharePoint directory.
upon successfully upload, () => { savingFile(); }); is called to save the file.
upload_SP() {
if (app.selectedFile.length == 0) {
alert("please select file to upload..");
app.isLoading = false;
return;
}
_.each(app.selectedFile, function (item, index) {
var blob = item.slice(0, item.size, 'image/jpg');
app.finalFile = new File([blob], app.renameFile[index] + '.jpeg', { type: 'image/jpg' });
});
var formData = new FormData();
_.each(app.finalFile, function (file, index) {
formData.append('file-' + index, file);
});
app.sp_action(app.parentId, app.folderId, app.finalFile.name, app.finalFile,
() => { savingFile(); });
}
},
Following method takes the arguments required to upload the file to the SP.
sp_action(parentId, folderId, fileName, data, callback = null) {
$.fileUploadSP(parentId, folderId, fileName, data, function (response) {
app.isSuccessful = response.isSuccessful;
if (response == "success") {
alert("Successfully Uploaded..");
app.messageDismissCountDown = 3;
if (callback) {
callback(response);
}else {
location.reload();
}
}
else {
clearCache(() => { });
app.message = response.message;
app.isLoading = false;
window.scrollTo(0, 0);
}
});
},
Following is AJAX call made to upload the file to the SharePoint.
window.$.getPathSP = function (parentId, forlderId, fileName) {
var origin = "https://graph.microsoft.com/v1.0/drives/" + parentId + "/items/" + forlderId +
":/" + fileName + ":/content"
return origin;
};
window.$.fileUploadSP = function (parentId, forlderId, fileName, data, callback) {
$.ajax({
type: 'PUT',
url: $.getPathSP(parentId, forlderId, fileName),
headers: graphHeader,
data: data,
contentType: false,
processData: false,
async: true,
crossDomain: true,
cache: false,
success: function (response) {
success(response, function () {
if (callback) {
callback("success");
}
});
},
failure: function (response) {
alert("failed")
failure(response, "fail");
},
error: function (response) {
alert("session was expired.. Please clear the local storage.")
error(response, callback);
}
});
};
I have the below JavaScript code to develop an app in Fuse Tools. There is one last error that I cannot seem to understand and that is that my variable b64data should be a global variable and is not updating it's value from the capturePhoto function and letting me send the updated value in the submitPhoto function to the server. It should send the base64 encoded value as the picture variable in my POST function. Any help is appreciated!
var Observable = require("FuseJS/Observable");
let ImageTools = require("FuseJS/ImageTools");
var FileSystem = require("FuseJS/FileSystem");
var Base64 = require("FuseJS/Base64");
var Camera = _camera;
var b64data;
var captureMode = Observable();
var flashMode = Observable();
function getCameraInfo() {
Camera.getCameraInfo()
.then(function(info) {
console.log("captureMode: " + info[Camera.INFO_CAPTURE_MODE]);
console.log("flashMode: " + info[Camera.INFO_FLASH_MODE]);
console.log("cameraFacing: " + info[Camera.INFO_CAMERA_FACING]);
console.log("supportedFlashModes: " + info[Camera.INFO_SUPPORTED_FLASH_MODES].join());
captureMode.value = info[Camera.INFO_CAPTURE_MODE];
flashMode.value = info[Camera.INFO_FLASH_MODE];
if (Camera.INFO_PHOTO_RESOLUTIONS in info) {
var availableResolutions = info[Camera.INFO_PHOTO_RESOLUTIONS];
availableResolutions.forEach(function(e) {
console.log(e.width + "x" + e.height);
});
photoResolution = availableResolutions[Math.floor(availableResolutions.length * 0.4)];
var options = {};
options[Camera.OPTION_PHOTO_RESOLUTION] = photoResolution;
Camera.setPhotoOptions(options)
.then(function() {
console.log("New photo options set: " + JSON.stringify(options));
})
.catch(function(error) {
console.log("Failed to set photo options: " + error);
});
}
})
.catch(function(err) {
console.log("Failed to get camera info: " + err);
});
}
getCameraInfo();
function nextFlashMode() {
if (flashMode.value == Camera.FLASH_MODE_AUTO) return Camera.FLASH_MODE_ON;
else if (flashMode.value == Camera.FLASH_MODE_ON) return Camera.FLASH_MODE_OFF;
else if (flashMode.value == Camera.FLASH_MODE_OFF) return Camera.FLASH_MODE_AUTO;
else throw "Invalid flash mode";
}
function setCaptureMode(cm) {
Camera.setCaptureMode(cm)
.then(function(mode) {
captureMode.value = mode;
console.log("Capture mode set to: " + mode);
})
.catch(function(err) {
console.log("Failed to set capture mode: " + err);
});
}
function capturePhoto() {
Camera.capturePhoto()
.then(function (photo) {
photo.save()
.then(function(filePath) {
console.log("Photo saved to: " + filePath);
var arrayBuff = FileSystem.readBufferFromFileSync(filePath);
var b64data = Base64.encodeBuffer(arrayBuff); // send this to the backend
photo.release();
})
.catch(function(error) {
console.log("Failed to save photo: " + error);
photo.release();
});
})
.catch(function (error) {
console.log("Failed to capture photo: " + error);
});
}
var isRecording = Observable(false);
var recordingSession = null;
function startRecording() {
isRecording.value = true;
Camera.startRecording()
.then(function (session) {
recordingSession = session;
})
.catch(function (error) {
console.log("Failed to start recording: " + error);
isRecording.value = false;
});
}
function stopRecording() {
isRecording.value = false;
recordingSession.stop()
.then(function (recording) {
router.push("VideoPage", recording.filePath());
})
.catch(function (error) {
console.log("Failed to stop recording: " + error);
});
recordingSession = null;
}
var cameraBack = true;
function flipCameraFacing() {
var front = Camera.CAMERA_FACING_FRONT;
var back = Camera.CAMERA_FACING_BACK;
Camera.setCameraFacing(cameraBack ? front : back)
.then(function (newFacing) {
cameraBack = newFacing == back;
getCameraInfo();
console.log("Camera facing set to: " + (newFacing == back ? "back" : "front"));
})
.catch(function (err) {
console.log("Failed to set camera facing: " + err);
});
}
function changeFlashMode() {
Camera.setFlashMode(nextFlashMode())
.then(function(newFlashMode) {
flashMode.value = newFlashMode;
console.log("Flash mode set to: " + flashMode.value);
})
.catch(function(err) {
console.log("Failed to set flash mode: " + err);
});
}
var name = Observable();
var email = Observable();
var market = Observable();
module.exports = {
name: name,
email: email,
market: market,
b64data: b64data,
submitPhoto: submitPhoto,
captureMode: captureMode,
setCaptureModePhoto: function () { setCaptureMode(Camera.CAPTURE_MODE_PHOTO); },
setCaptureModeVideo: function () { setCaptureMode(Camera.CAPTURE_MODE_VIDEO); },
capturePhoto: capturePhoto,
startRecording: startRecording,
stopRecording: stopRecording,
isRecording: isRecording,
flipCameraFacing: flipCameraFacing,
flashMode: flashMode,
changeFlashMode: changeFlashMode,
}
function submitPhoto(){
console.log("name: "+name);
console.log("email: "+email);
console.log("market: "+market);
fetch('http://fanbeauties.com/app/submit-photo.php?pass=MY_PASS', {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: '&name='+name+'&email='+email+'&market='+market+'&picture='+b64data
});
};
May be because of you are declaring b64data again in capturePhoto function on line 72 in your shared code.
try
b64data = ...
instead of
var b64data = ...
I am developing an app with an audio upload this code worked before
i update cordova 5 to 6. I am not really sure the issue is cause the update.
The error in my logs is
"error in coipy
console-via-logger.js (174,23)"
var url = "domainname/app/upload.php";
var targetPath = cordova.file.externalRootDirectory;
var name1 = $scope.sound.name;
var extension = $scope.sound.file.split(".").pop();
var filepart = Date.now();
var filename = filepart + "." + extension;
console.log("new filename is " + filename);
var options = {
fileKey: "file",
fileName: filename,
chunkedMode: false,
params: { 'directory': 'upload', 'fileName': filename, 'name': name1 }
};
window.resolveLocalFileSystemURL(targetPath, function (d) {
window.resolveLocalFileSystemURL($scope.sound.file, function(fe) {
fe.copyTo(d, filename, function(e) {
console.log('success inc opy');
$ionicPopup.alert({
title: 'Save OK',
template: 'Save OK'
});
console.dir(e);
$scope.sound.file = e.nativeURL;
$scope.sound.path = e.fullPath;
console.log($scope.sound.file);
console.log($scope.sound.path);
$cordovaFileTransfer.upload(url, $scope.sound.file , options).then(function (result) {
console.log("SUCCESS: " + JSON.stringify(result.response));
}, function (err) {
console.log("ERROR: " + JSON.stringify(err));
}, function (progress) {
// PROGRESS HANDLING GOES HERE
});
Sounds.save($scope.sound).then(function() {
$ionicHistory.nextViewOptions({
disableBack: true
});
});
}, function(e) {
console.log('error in coipy');console.dir(e);
});
}, function(e) {
console.log("error in inner bullcrap");
console.dir(e);
});
I am angularjs newbie. I try to use ionic framework to do a practice, so that will use angularjs. And I got a little problem. I want to before insert data to check this data have exist, if not exist that will insert a new data.
On this method getContent.then(function(res){}), I will check this return res.length, if equal 0 I want insert this data. When I run, that will execute this console, and obj is have data. But at finally, I want get all data, but the data is empty.
But I found If I remove this insert method outside getContent.then(function(res){}), it's work. I have no idea how to fix this problem and cause this reason.
Thanks your help.
This is my Controller code
angular.module('starter.controllers', ['sqlite.services'])
.controller('TestCtrl', function($scope, $http, Tests, SQLService) {
SQLService.setup();
var new_tests = new Array();
$http.get('https://XXXXX').then(function(response){
var datas = response.data;
for (data_ in datas) {
var obj = {
id: datas[data_].content_id,
title: datas[data_].title,
url: datas[data_].url,
content: datas[data_].content
};
var getContent = SQLService.get_one(obj.id);
getContent.then(function(res) {
console.log('res ' , res);
console.log('res ' , res.length); // length get 0
if(res.length == 0) {
console.log('insert obj ' , obj);
console.log('SQLService ' , SQLService);
SQLService.insert(obj);
}
else if (res.length == 1) {
console.log('edit obj ' , obj);
}
});
// SQLService.insert(obj); // If I write insert code here is work for me
new_tests.push(obj);
}
})
.finally(function() {
SQLService.all().then(function (results) {
$scope.tests = results;
console.log('results ' , results);
});
});
This is my sql_service.js
angular.module('sqlite.services', [])
.factory('SQLService', function($q) {
var db;
function createDB() {
try {
if (window.cordova) {
$cordovaSQLite.deleteDB("my.db");
db = $cordovaSQLite.openDB({name: 'my.db'}); // device
}
else{
db = window.openDatabase("my.db", '1', 'my', 1024 * 1024 * 100); // browser
}
db.transaction(function(tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS pixnet (id integer not null primary key autoincrement, content_id text, title text, url, text, content text)", []);
});
}
catch(err) {
console.log('Error processing SQL: ' + err);
}
console.log('database created');
}
function insertNewContent(newContent) {
console.log('--insert--');
return promisedQuery("INSERT INTO pixnet (content_id, title, url, content) VALUES ('" + newContent.id + "', '" + newContent.title + "', '" + newContent.url + "', '" + newContent.content + "')", defaultResultHandler, defaultErrorHandler);
}
function getContents() {
return promisedQuery("SELECT * FROM pixnet", defaultResultHandler, defaultErrorHandler);
}
function updateContent(content){
console.log('update content ' , content);
return promisedQuery("UPDATE pixnet SET title='" + content.title + "', content='" + content.content + "' WHERE content_id = '" + content.id + "'", defaultResultHandler, defaultErrorHandler);
}
function getContent(content_id) {
return promisedQuery("SELECT * FROM pixnet WHERE content_id = '" + content_id + "'", defaultResultHandler, defaultErrorHandler);
}
function defaultResultHandler(deferred) {
return function(tx, results) {
console.log('defaultResultHandler results ' , results);
var len = results.rows.length;
var output_results = [];
for (var i=0; i<len; i++){
var t = {
'id': results.rows.item(i).id,
'content_id': results.rows.item(i).content_id,
'title': results.rows.item(i).title,
'url': results.rows.item(i).url,
'content': results.rows.item(i).content
};
output_results.push(t);
}
deferred.resolve(output_results);
}
}
function defaultErrorHandler(deferred) {
return function(tx, results) {
var len = 0;
var output_results = '';
deferred.resolve(output_results);
}
}
function promisedQuery(query, successCB, errorCB) {
var deferred = $q.defer();
db.transaction(function(tx){
tx.executeSql(query, [], successCB(deferred), errorCB(deferred));
}, errorCB);
return deferred.promise;
}
return {
setup: function() {
return createDB();
},
insert: function(content) {
return insertNewContent(content);
},
edit: function(content) {
return updateContent(content);
},
get_one: function(content_id) {
return getContent(content_id);
},
all: function() {
return getContents();
}
}
});
I believe what's happening is that the 'deferred' you create in promiseQuery is never resolved:
function promisedQuery(query, successCB, errorCB) {
var deferred = $q.defer();
db.transaction(function(tx){
tx.executeSql(query, [], successCB(deferred), errorCB(deferred));
}, errorCB);
return deferred.promise;
}
Since you are using cordova sqlite plugin, looking at the source code we see the third argument of the 'transaction' function is the success callback.
https://github.com/brodysoft/Cordova-SQLitePlugin/blob/master/www/SQLitePlugin.js#L74
So this means you want to resolve your promise in either of those callbacks. Try the following:
function promisedQuery(query, successCB, errorCB) {
var deferred = $q.defer();
db.transaction(function(tx){
tx.executeSql(query, [], successCB(deferred), errorCB(deferred));
}, errorCB, deferred.resolve);
return deferred.promise;
}
Passing the deferred.resolve function into the success callback (the last argument of transaction) will get it called when the transaction finishes.
angular.module('starter.controllers', ['sqlite.services'])
.controller('TestCtrl', function($scope, $http, Tests, SQLService) {
SQLService.setup();
var new_tests = new Array();
var call_async_in_loop = function(obj) {
var getContent = SQLService.get_one(obj.id);
getContent.then(function(res) {
console.log('res ', res);
console.log('res ', res.length); // length get 0
if (res.length == 0) {
console.log('insert obj ', obj);
console.log('SQLService ', SQLService);
SQLService.insert(obj);
} else if (res.length == 1) {
console.log('edit obj ', obj);
}
});
}
$http.get('https://XXXXX').then(function(response) {
var datas = response.data;
for (data_ in datas) {
var obj = {
id: datas[data_].content_id,
title: datas[data_].title,
url: datas[data_].url,
content: datas[data_].content
};
call_async_in_loop(obj)
new_tests.push(obj);
}
})
.finally(function() {
SQLService.all().then(function(results) {
$scope.tests = results;
console.log('results ', results);
});
});
You loosing the reference to obj because of the async call SQLService.get_one(obj.id). When the promise is resolved the for loop is already finished. So u have to create a closure to keep reference to obj.
I am tring to upload a file using angular $http method to node backend
I want to upload the form with additional form fields.
This is my code
var data = new FormData();
data.append('title', 'sometitle');
data.append('uploadedFile', $scope.uploadedFile);
FileService.upload(url, data, function(data, status) {
if(status===HTTP_OK) {
$scope.uploadSuccess = true;
$scope.showUploadProgressBar = false;
} else {
// error occured
console.log(data);
}
});
FileService
FileService.upload = function(url, data, callback) {
$http({
method : 'POST',
url : url,
data : data,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success(function(data, status) {
callback(data, callback);
}).error(function(data, status) {
callback(data, status);
});
};
I am using node multiparty module for file upload. I am receiving the file correctly. But the field value for title is undefined.
I don't know why title value is undefined
Node.js backend file upload handler
var form;
if(options.uploads.tempDir) {
form = new multiparty.Form({uploadDir : options.root + '/' + options.uploads.tempDir});
} else {
form = new multiparty.Form();
}
form.on('file', function(name, receivedFile) {
var tmpPath = receivedFile.path,
fileName = receivedFile.originalFilename,
targetDirectory = uploadDirectory + '/' + req.params.id,
targetPath = targetDirectory + '/' + fileName,
file = {
filePath : targetPath,
tempPath : tmpPath,
fileName : fileName,
size : receivedFile.size
};
fileUploadStatus.file = file;
// move file
fse.move(tmpPath, targetPath, function(err) {
if(err) {
console.log('Error moving file [ ' + targetPath + ' ] ' + JSON.stringify(err));
}
});
});
form.on('error', function(err) {
fileUploadStatus.err = err;
req.fileUploadStatus = fileUploadStatus;
next();
});
form.on('close', function() {
req.fileUploadStatus = fileUploadStatus;
next();
});
form.on('field', function(name, value) {
console.log('field called');
console.log(name);
console.log(value);
req.body = req.body || {};
req.body[name] = value;
});
// ignoring parts. Implement any other logic here
form.on('part', function(part) {
var out = new stream.Writable();
out._write = function (chunk, encoding, done) {
done(); // Don't do anything with the data
};
part.pipe(out);
});
// parsing form
form.parse(req);