Angular and cloudinary integration error? - angularjs

I am using clodinary - angular app in github mentioned below
https://github.com/cloudinary/cloudinary_angular
But in that app, it shows only uploading image with image preset.But I need to upload image with API key.I changed my code as
In my app.js
app.config(['cloudinaryProvider' , function (cloudinaryProvider) {
cloudinaryProvider
.set("cloud_name", "********")
.set("api_key", "**********")
.set("api_secret", "****************");
//.set("upload_preset", "*******");
}
]);
I commented upload preset and changed 'unsigned' to 'signed' in cloudinary dashboard.
In my service
promise = $upload.upload({
url: "https://api.cloudinary.com/v1_1/" + cloudinary.config().cloud_name + "/upload",
data: {
api_key: cloudinary.config().api_key,
api_secret: cloudinary.config().api_secret,
tags: 'myphotoalbum',
context: 'photo=' + title,
file: file
}
}).progress(function (e) {})
.success(function (data, status, headers, config) {
return data;
}).error(function (data, status, headers, config) {
return data;
});
But it shows "Bad Request Error".How can I fix this issue.Please help me and thanks in advance.

Related

large files failing download in nodejs

I have a service that builds a csv file, and returns it to the user. Currently using expressjs v4.14, nodejs v8.7.0. My problem is that I get a download failed due to 'network error' in chrome when I call the service for it to create a large csv file. With smaller files, the service works fine. I can also browse to the /temp/ folder, and the entire expected file exists. In each case of 'things i tried', I was able to download smaller files but not the large ones.
Service:
download.post('/csv', (req, res, next) => {
res.status(200).header('Content-Type', 'text/csv');
const newUUID = uuid.v1();
let ws: WriteStream = fs.createWriteStream(`${__dirname}/../../temp/${newUUID}.csv`);
ws.on('finish', () => {
res.download(`${__dirname}/../../temp/${newUUID}.csv`);
});
//csv file built here
ws.write('huge stuff easily 50k rows and 10 mb file');
ws.end();
});
Chrome Error:
Chrome's network tab and developer console do not give me any indication of what happened. This download popup is all I get. I cleared everything in cookies/cache just in case and it did not help.
Things I tried:
writing chunks directly to response stream.
using readable stream https://nodejs.org/api/stream.html#stream_readable_streams , converting String into bytes and piping it.
creating a file locally (writestream) and streaming it back (readstream pipe into res)
res.download(file) after writestream creating local file ended
Update:
Ended up trying the service from postman and it worked, so I think it is an angularjs issue.
Angularjs
$http({
cache: false,
url: "/download/csv",
headers: {
'accept': 'text/csv'
},
method: 'POST',
data: {
rows: rows,
title: title ? title : ''
}
}).success(function (data, status, headers, config) {
var anchor = angular.element('<a/>');
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'csv_info.csv'
})[0].click();
}).error(function (data, status, headers, config) {
});
Turned out to be a limitation from href attribute from the anchor tag created in angularjs. This was solved using FileSaver:
$http({
cache: false,
url: "/download/csv",
headers: {
'accept': 'text/csv'
},
method: 'POST',
data: {
rows: rows,
title: title ? title : ''
}
}).success(function (data, status, headers, config) {
var file = new File([data], "info.csv", {type: "text/csv;charset=utf-8"});
saveAs(file);
}).error(function (data, status, headers, config) {
});

Angularjs - 500 (Internal Server Error) on $http Post

I am new to Ionic and angular. I am building a sample with ionic framework using angular.js. I want to call WebApi through $http post method. I checked this(ionic-proxy-example) solution and I am trying to implement the same using my api. When I call the api provided in above example in my sample project, I get the records but its not working with my api. It throws 500 internal error.
Here is my app.js
angular.module('myApp', ['myApp.controllers', 'myApp.services'])
.constant('ApiEndpoint', {url: 'http://localhost:8100/api'})
Services.js
angular.module('myApp.services', [])
.factory('Api', function($http, $q, ApiEndpoint) {
console.log('ApiEndpoint', ApiEndpoint)
var getApiData = function() {
var q = $q.defer();
var data = {
Gameweek_ID: '179',
Vender_ID: '1',
Language:'en'
};
var config = {
headers : {
"Content-Type": "application/json; charset = utf-8;"
}
};
$http.post(ApiEndpoint.url, data, config)
.success(function (data, status, headers, config) {
// $scope.PostDataResponse = data;
alert('success');
console.debug("response :" + data);
q.resolve(data);
})
.error(function (data, status, header, config) {
// $scope.ResponseDetails = "Data: " + data +
alert('error');
console.debug("error :" + data);
q.reject(data);
});
return q.promise;
}
return {getApiData: getApiData};
})
controllers.js
angular.module('myApp.controllers', [])
.controller('Hello', function($scope, Api) {
$scope.employees = null;
Api.getApiData()
.then(function(result)
{console.log("result is here");
jsonresponse = result.data;
$scope.employees = jsonresponse;}
)
});
And Ionic.Project File
{
"name": "Multilingual",
"app_id": "4b076e44",
"proxies": [
{
"path": "/api",
"proxyUrl": ""
}
]}
I am trying to understand the problem and checked multiple methods to call the api. Surprisingly, it works with ajax post call without any CORS errors. As I am using Angular, I am trying to get this done through $http post. I feel it is some minor issue but I am not able to figure out. Will be grateful for solutions. Thank you.
You've set the content type to json so the sever is expecting a json string but isn't receiving a properly formatted json string as you're sending through an object and hence the error.
Where you have $http.post(ApiEndpoint.url, data, config) change it to $http.post(ApiEndpoint.url, JSON.stringify(data), config).
If that doesn't work, change your content type to application/x-www-form-urlencoded and update this line $http.post(ApiEndpoint.url, data, config) to $http.post(ApiEndpoint.url, $httpParamSerializer(data), config) , don't forget to inject the $httpParamSerializer function.
The problem is that you are sending a POST with $http.post request instead of a GET request with $http.get
Try as below-
$http({
url: ApiEndpoint.url,
method: "POST",
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).Success(..rest code goes here..)
In WebAPI, when we pass more than one object in POST method, we get 500 internal error and hence we use ViewModel in such scenarios(talking about asp.net MVC).

angular file upload+sails skipper upload no file

I'm using angularJS for my frontend and sails.js/expressjs for my backend. I'm implementing a file upload function using ng-file-upload, and strangely the file never seem to upload to the server successfully... this is my angularJS code:
$scope.$watch('data.chosenImageFile', function() {
if ($scope.data.chosenImageFile) {
console.log($scope.data.chosenImageFile);
$scope.upload = $upload.upload({
url: '/upload_user_avatar',
method: 'POST',
file: $scope.data.chosenImageFile
}).progress(function(evt) {
console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
console.log(data);
});
}
});
And this is my sails.js code:
uploadUserAvatar: function(req, res) {
req.file('avatar').upload(function(err, files) {
if (err) return res.send(500, err);
return res.json({
message: files.length + ' file(s) uploaded successfully!',
files: files
});
});
},
And I always get the following response from server:
Object {message: "0 file(s) uploaded successfully!", files: Array[0]}
When I check the corresponding server upload destination folder, there's nothing.... anyone know why or could provide some help? Will really appreciate it!
Ok this question isn't a really smart one, I figured out where the problem is: the default fileFormDataName for ng-file-upload is "file", since I'm using req.file('avatar') on the server side, I should really add the following setting option in my angular code:
fileFormDataName: 'avatar',
which makes it look like so:
$scope.$watch('data.chosenImageFile', function() {
if ($scope.data.chosenImageFile) {
console.log($scope.data.chosenImageFile);
$scope.upload = $upload.upload({
url: '/upload_user_avatar',
method: 'POST',
fileFormDataName: 'avatar',
file: $scope.data.chosenImageFile
}).progress(function(evt) {
console.log('progress: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
console.log(data);
});
}
});
UPDATE
According to #Anupam Bhaskar's request, I've also added my HTML code for a file upload dropzone below:
<div ng-file-drop ng-if="!data.isUploading" ng-model="data.chosenImageFile" class="avatar-dropzone pull-left" drag-over-class="upload-dropzone" ng-file-change="avatarUpload.fileSelected('/upload_user_avatar', data.user, data)" multiple="false" allow-dir="true" accept="*">
<div class="text-center upload-sign">+</div>
</div>

How do I send an image file for download from Node backend to Angular frontend?

I have an app with an Express backend, and angular frontend. I am trying to create a file download link for image files, but I am running into problems sending the file from express to angular. My angular looks like this...
scope.download = function(file){
http({method:'GET', url:'/get_download/' + file.id}).
success(function(data, status, headers, config) {
var element = angular.element('<a/>');
element.attr({
href: 'data:attachment;charset=utf-8,' + encodeURIComponent(data),
target: '_self',
download: file.name
})[0].click();
}).
error(function(data, status, headers, config) {
console.log("THERE WAS AN ERROR");
});
}
I have tried several different things on the express side each of which are producing different errors.
First I tried the following...
res.download("my_file_path", "my_file_name", function (err) {
if (err) {
console.log("ERROR");
console.log(err);
}
});
And got this error...
path.js:360
throw new TypeError('Arguments to path.join must be strings');
^
TypeError: Arguments to path.join must be strings
Then I tried...
fs.readFile("my_file_path", function(err, data) {
res.writeHead(200, { 'Content-disposition': 'attachment' });
res.end(data);
});
Which downloaded the file, but it got corrupted along the way, and would not open.
Any suggestions would be appreciated.

When setting http authorization headers the AngularJS app crashes

I want to make a request to the twitter api and get the current logged in userfeed.
I tryed the twitter api with "apigee" and everything works fine. Even when copying the Authorization header from "apigee" into "postman" I get back data.
Well but when I try to make the http-request in my angular-app, the whole app stops working.
In the browser there ist just the output "{{message}}" and the console prints two error messages:
Uncaught SyntaxError: Unexpected identifier :3000/javascripts/app.js:211
Uncaught Error: No module: app angular.min.js:17
The code in my app looks like this
app.controller('TwitterCtrl', function($scope, $http) {
var url = "https://api.twitter.com/1.1/statuses/home_timeline.json";
$http.get(url,
{headers: {
'Authorization':
Oauth oauth_consumer_key = "xxxx",
oauth_signature_method="HMAC-SHA1"
oauth_timestamp="1401883718",
oauth_nonce="840988792",
oauth_version="1.0",
oauth_token="xxxx",
oauth_signature="xxx"
}})
.then(function (data) {
$scope.data = data.data;
console.log(data);
});
Can anyone help me or tell me what I'm doing wrong.
Kevin
try this way:
app.controller('TwitterCtrl', function($scope, $http) {
var url = "https://api.twitter.com/1.1/statuses/home_timeline.json";
$http.get(url, {
headers: {
'Authorization':
'Oauth oauth_consumer_key = "xxxx",' +
'oauth_signature_method="HMAC-SHA1",' +
'oauth_timestamp="1401883718",' +
'oauth_nonce="840988792",' +
'oauth_version="1.0",' +
'oauth_token="xxxx",' +
'oauth_signature="xxx"'
}
}).then(function (data) {
$scope.data = data.data;
console.log(data);
});

Resources