Upload photo and video together with angularjs - angularjs

I need to upload photos and videos together.
I am using the ng-file-upload
my mvc controller :
[HttpPost]
public ContentResult Add(List<HttpPostedFileBase> file, VideoViewModel item)
{
return Content(_output.ConvertToJson(), "application/json");
}
my javascript codes :
$scope.item = {
Address: '',
Name: ''
};
$scope.files = [];
$scope.file = null;
$scope.video = null;
$scope.response = {};
$scope.confirmAdd = function () {
if ($scope.add_form.$valid) {
$scope.files[0] = $scope.file;
$scope.files[1] = $scope.video;
$upload.upload({
url: 'User/Add',
method: 'POST',
data: $scope.item,
file: $scope.files,
}) .progress(function (evt) {
$scope.percent = parseInt(100.0 * evt.loaded / evt.total);
}).success(function (data, status, headers, config) {
$scope.response = data;
}).error(function (err) {
$scope.percent = 0;
});
} else {
$scope.add_form.submitted = true;
}
}
$scope.onFileSelect = function ($files) {
$scope.file = $files[0];
};
$scope.onVideoSelect = function ($files) {
$scope.video = $files[0];
};
error :
IIS 8.0 Detailed Error - 404.13 - Not Found
The request filtering module is configured to deny a request that exceeds the request content length
Most likely causes:
Request filtering is configured on the Web server to deny the request because the content length exceeds the configured value
How do I solve the problem?

Related

downloading text file in postman but not in browser using restapi in angularjs

$scope.newFile is my response from backend. Actually my response should be a text file, which is working in postman.But in browser , I am getting
Cannot GET
/Organizer/%7B%22data%22:%22id/tname/temail/tphone/twebsite/tvenue/ttags/n83/tAny%20Name/ta#b.com/t9009009009/thttp://www.anyname.com/tHall%20A/ttag1,%20tag2,%20tag3/nsunitha/tsunitha#gmail.com/t55555541/thttp://www.sunitha.com/nSuhasini/tsuha#gmail.com/t955555544/thttp://www.suha.com/nRaichel/traichel#gmail.com/t955548458/thttp://www.raichel.com/n%22,%22status%22:200,%22config%22:%7B%22method%22:%22GET%22,%22transformRequest%22:[null],%22transformResponse%22:[null],%22jsonpCallbackParam%22:%22callback%22,%22headers%22:%7B%22Authorization%22:%22Token%2013946cc6c575d61b042b01b6905f1d239b3d9b08%22,%22Accept%22:%22application/json,%20text/plain,%20*/*%22%7D,%22url%22:%22http://http://localhost/1290//entity/campaigns/download_exhibitors/%22%7D,%22statusText%22:%22OK%22,%22xhrStatus%22:%22complete%22%7D
Service.js
var url =' http://localhost/1290/';
function downloadExhibitor() {
var token = 129821sahh;
var auth = "Token" + ' ' + token;
var config = {
headers: {
'Content-Type': 'text/plain',
'Authorization': auth
}
}
return $http.get(url + 'entity/campaigns/download_exhibitors/', config)
.then(successHandler, errorHandler);
}
function successHandler(response){
/* we've got file's data from server */
return response.data;
}
function errorHandler(error){
/* we've got error response from server */
throw new Error('ERROR ' + error);
}
and eventually the service invocation
JS:
$scope.newFile = "";
service.downloadExhibitor()
.then(function(data){
$scope.newFile = data;
}, function(error){
console.log(error);
});
HTML:
<button class="btn" ng-click="downloadAllExhibitors();">
<a ng-href="{{newFile}}" target="_blank">Download</a></button>
You can try below code in controller...
var file = new Blob([data], {
type : 'text/plain'
});
if (navigator.userAgent.indexOf('MSIE') !== -1
|| navigator.appVersion.indexOf('Trident/') > 0) {
window.navigator.msSaveOrOpenBlob(file);
} else {
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
Following code in controller made my work simple , and it downloaded the file finally.
var file = new Blob([data], {
type: 'text/plain'
});
if (navigator.userAgent.indexOf('MSIE') !== -1 ||
navigator.appVersion.indexOf('Trident/') > 0) {
window.navigator.msSaveOrOpenBlob(file);
} else {
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(file, {
type: "text/plain"
});
a.download = "filename.csv";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}

using ng-file-upload to upload file to hard drive

I want to use ng-file-upload to upload files to hard drive in the server
this.uploadFiles = function(files, errFiles) {
this.files = files;
this.errFiles = errFiles;
angular.forEach(files, function(file) {
file.upload = Upload.upload({
url: 'C:\Java\logs',
data: {file: file}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
this.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 *
evt.loaded / evt.total));
});
});
}
when I use this code I get this error
angular.js:10765 XMLHttpRequest cannot load file:///C:/Javalogs. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
that what I did but it didn't work
this.uploadFiles = function(file, errFiles) {
Upload.dataUrl(file[0], true).then(function (base64Url) {
var filename = 'test.jpg';
var a = document.createElement("a");
var myDocument = getFileContainer(base64Url);
var blob = new Blob([myDocument.data], {type: 'image/jpg'});
var file = new File([blob], 'imageFileName.jpg');
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
var elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(file);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
})
the picture is generated but I can't view it
I send them via a base64 url to the backend. It depends on which data you need but it should roughly look like the following code.
function getMimeTypeFromUrl(imageUrl) {
return imageUrl.substring(imageUrl.indexOf(':') + 1, imageUrl.indexOf(';'));
}
function getDataFromUrl(imageUrl){
return imageUrl.substring(imageUrl.indexOf(',') + 1);
}
function getFileContainer(imageUrl, file){
return {
data:getDataFromUrl(imageUrl),
mimeType: getMimeTypeFromUrl(imageUrl),
filename: file.name,
}
}
this.uploadFiles = function(files, errFiles) {
Upload.dataUrl(file, true).then(function (base64Url) {
myDocument = getFileContainer(base64Url, file);
//here you have to post myDocument
}
}
Upload is a service of ng-file-upload, which loads the file to the browser as a base64 url.
I hope I could help you.

Download PDF using Angular

I'm trying to download PDF from a WebApi using Angular but the file is only 15 bytes. If I log the data being received from the WebApi it's an arraybuffer with the expected size
The WebApi
[HttpGet]
public HttpResponseMessage MatchRegistrationReport(int matchId)
{
try
{
var gen = new MSReports.Components.MatchRegistration();
byte[] bytes = gen.GeneratePDF(matchId, 10);
var stream = new MemoryStream(bytes);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
//Content = new ByteArrayContent(bytes)
};
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = gen.ReportName + ".pdf"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}
catch (Exception ex)
{
Log.Error(ex.Message);
return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
The Angular controller
$scope.Print = function () {
$scope.message = "Downloading";
reportResource.printMatchRegistration($scope.match.Id).then(function (data, status, headers, config) {
var file = new Blob([data], {
type: 'application/csv'
});
//trick to download store a file having its URL
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = 'MatchRegistration.pdf';
document.body.appendChild(a);
a.click();
//$scope.message = "Completed";
}, function (data, status, headers, config) {
$scope.message = "A error occurred";
});
}
and the resource
printMatchRegistration: function (matchId) {
return $http({
method: 'get',
url: this.getApiPath() + "MatchRegistrationReport?matchId=" + matchId,
headers: {
'Content-type': 'application/pdf',
},
responseType: 'arraybuffer'
});
I believe it has something to do with the content-type but can' figure out what.
Hi just found the answer
Change to this
reportResource.printMatchRegistration($scope.match.Id).then(function (response) {
var file = new Blob([response.data], {
type: 'application/pdf'
});
and this
printMatchRegistration: function (matchId) {
var data = { 'matchId': matchId };
return $http({
method: 'get',
url: this.getApiPath() + "MatchRegistrationReport",
params: data,
headers: {
'Content-type': 'application/pdf',
},
responseType: 'arraybuffer'
});
},

http.post angularjs 404 error

I'm trying to post form data to a mongodb (moongose) using the angularjs http.post method and I'm getting a 404 error not sure I'm doing this correctly. It complains it cant find the url -> POST http://localhost:5000/tournaments/56bf2ea58e5ea932088ff356/games 404 (Not Found)
###### This is my api router
router.post('/tournaments/:id/games', function(req, res) {
var newGame = {};
newGame.id = req.body.id;
newGame.gameDate = req.body.gameDate;
newGame.homeTeam = req.body.homeTeam;
newGame.awayTeam = req.body.awayTeam;
newGame.homeTeamScore = req.body.homeTeamScore;
newGame.awayTeamScore = req.body.awayTeamScore;
newGame.hadOT = req.body.hadOT;
newGame.hadSO = req.body.hadSO;
Tournament.update({ "_id": req.params.id}, {$push: {games: newGame}}, function(err, model) {
if(err) {
res.send(err)
} else {
res.json(model)
}
});
});
this is in the controller
vm.isEditing = false;
vm.newGame = {
awayTeam: '',
homeTeam: '',
homeTeamScore: 0,
awayTeamScore: 0
};
vm.showModal = function() {
vm.isEditing = true;
}
vm.hideModal = function() {
vm.isEditing = false;
vm.addGameForm.$setPristine();
vm.isSaving = true;
}
vm.addGame = function() {
vm.isSaving = true;
vm.newGame.id = vm.selectedTournament.games.length + 1;
$http({
method : 'POST',
url : '/tournaments/'+tournamentId+'/games',
data : $.param($scope.vm.newGame),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(response){
$scope.vm.newGame = {};
$scope.games = response;
console.log(response);
})
.error(function(data) {
console.log('Error: ' + data);
});
vm.addGameForm.$setPristine();
vm.hideModal();
}

How to get twitter feeds from twitter api in angularjs

I am using index.html for displaying the feeds.
My app.js is-
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result +=chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
function twitterCallback(data){
alert(responseJson.status.text);
}
var app=angular.module('store',[]);
app.controller('indexController', function($scope, $http) {
var unixtime=Math.round((new Date()).getTime() / 1000.0),
nonce=randomString(32,'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
var httpMethod = 'GET',
url = 'https://api.twitter.com/1.1/statuses/home_timeline.json',
parameters = {
oauth_consumer_key : 'AD6SEy1m3XkggNTuYw5SUl4dv',
oauth_nonce : nonce,
oauth_signature_method : 'HMAC-SHA1',
oauth_timestamp : unixtime,
oauth_token : '3131481153-I9k4ZvdnePO42lOH0EJQNQcAHoyim6XrFFzFk90',
oauth_version : '1.0',
screen_name:'twitterapi',
callback:'twitterCallback'
},
consumerSecret = 'xxxxx',
tokenSecret = 'xxxxx',
signature = oauthSignature.generate(httpMethod, url, parameters, consumerSecret, tokenSecret,
{ encodeSignature: true});
$http.jsonp(url, {
headers: {
'Authorization':
'OAuth oauth_consumer_key="AD6SEy1m3XkggNTuYw5SUl4dv",' +
'oauth_signature_method="HMAC-SHA1",' +
'oauth_timestamp='+unixtime +
'oauth_nonce='+nonce +
'oauth_version="1.0",' +
'oauth_token="3131481153-I9k4ZvdnePO42lOH0EJQNQcAHoyim6XrFFzFk90",'+
'oauth_signature='+signature
},
params:{screen_name:'twitterapi',
}
}).success(function (data)
{
$scope.tweets = data;
}).error(function(data){
console.log('error');
}) ;
});
How to connect to twitter and define twitter-callback?Please specify how to connect with twitter.
I am getting
GET home_timeline.json?screen_name=twitterapi
400 Bad Request

Resources