C# with kendo ui - client send file to server - file

I'm trying to send a .xlsx file to my REST API using Kendo Ui. But I'm lost.
I was able to call my service, but I can't get the file. I believe I'm sending it wrong.
I don't need to save the file. I only need to read the .xlsx file to import the data to my database.
html (don't have a form):
<div>
<input name="files" id="files" type="file" />
<button id="importButton">Import</button>
</div>
js:
$("#files").kendoUpload({
async: {
autoUpload: true
},
select: onSelect
});
$("#importButton").kendoButton({
click: onImport
});
function onImport() {
var formData = new FormData();
jQuery.each(jQuery('#files')[0].files, function (i, file) {
formData.append('file-' + i, file);
});
$.ajax({
type: "POST",
url: url,
data: formData,
processData: false,
cache: false,
success: function (result) {
alert("Ok");
},
error: function (result) {
alert("Not Ok");
}
});
}
Server-side:
[HttpPost, Route("import")]
public void Import()
{
var streamProvider = new MultipartMemoryStreamProvider();
Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(streamProvider).ContinueWith((tsk) =>
{
foreach (HttpContent ctnt in streamProvider.Contents)
{
Stream stream = ctnt.ReadAsStreamAsync().Result;
// do something
}
});
}

Got it!
$("#files").kendoUpload({
async: {
withCredentials: false,
saveUrl: url,
autoUpload: true
},
select: onSelect
});
This answer helped me: Cross domain upload
#Brett was right, implement the kendUpload was the way.
I thought the Import button should do the magic, but I only need to use kendoUpload.
Thanks!!

Related

How to get value from router request?

I have created an angular app. In this app, I want to add a search. for this, I have a textbox and a button. Textbox name is name="search"
I have a get method in API.
router.get('/allActivities', (req, res) => {
Activity.find({ name: req.body.search }, (err, activities) => {
if(err) {
res.json({success: false, message: err});
} else {
if(!activities) {
res.json({success: false, message: 'No recent activities found'});
} else {
res.json({success: true, activities: activities});
}
}
})
});
This is the get request. In this, I'm trying to get the text box value from angular front end
Activity.find({ name: req.body.search }, (err, activities) =>
This is MongoDB
But I'm not getting any output. The matter here is I'm not getting a value for this "req.body.search" which I used to get text box value. can anybody tell me how to do this?
if I put
Activity.find({ name: 'Roshini' }, (err, activities) =>
like this, I'm getting the output. So pretty sure that I'm not getting textbox value to this get method correctly, :/
Html side
<input ng-model="search">
Angular Controller
$http({
method: 'GET',
url: '/allActivities?search='+$scope.search
}).then(function (response) {
$scope.activities = response.data || response
}, function (response) {
alert(response)
}
);
and on backend access it by req.query.search or req.params.search rather than req.body.search

How to send form data from Angularjs to Django

I did the application on the sample from this lesson. Here, using DRF, a list of all added games is displayed on the page. I would really like to learn how to write a simple form of adding a new record to the database (two fields: title and description [as in the example]).
With js, I'm not very familiar with so far, so I do not know which side to get close to solving the problem.
$scope.saveUser = function(event) {
postForm({ id: 0 }, $('#FormName'), $scope, function(data) {
})
}
function postForm(postInfo, form, $scope, callback,) {
var postData = new FormData(form.get(0));
$.each(postInfo, function(key, value) {
postData.append(key, value);
});
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: postData,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
headers: {
"X-CSRFToken": app.getStorage("csrftoken")
},
beforeSend: function() {
$('#loading-image').show();
},
complete: function() {
$('#loading-image').hide();
if(typeof saveButtonId !== typeof undefined) {
$('#'+saveButtonId).removeAttr('disabled');
}
},
success: function(data) {
},
error: function(data) {
//
}
});
};
you'd be updating code in your mysite/backend folder to have some incoming route to insert data into django db using some serializer
sorry I don't have more specific details, but just wanted to convey the general idea
Here's some more information on Django serializers: http://www.django-rest-framework.org/api-guide/serializers/
another tutorial on adding an additional route to django could help

Uploading picture with Angular, Express, Mongoose

I'm trying to upload and store picture with Mongoose, Express and Angular. I've picked here the next solution:
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('change', function(){
$parse(attrs.fileModel).assign(scope,element[0].files)
scope.$apply();
});
}
};
}])
And the next function in controller:
$scope.uploadFile=function(){
var fd = new FormData();
angular.forEach($scope.files,function(file){
fd.append('file',file);
});
$http.post('http://' + host + ':3000/users/' + $scope.selectedTask._id,fd,
{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function(d){
console.log('yes');
})
}
And html:
<input type = "file" file-model="files" multiple/>
<button ng-click = "uploadFile()">upload me</button>
<li ng-repeat="file in files">{{file.name}}</li>
But for some reason all I'm getting in my endpoint is an empty request object. I'm checking it with the following code in express.js:
user.route('/users/:id')
.post(function (req, res, next) {
console.log(req.body);
})
I think the problem is that I don't know how to store something that is larger then 16MB.
In this example you will see how to store the file you are sending in to your server directory and then pick them up from there and save them. You can also directly save them.
First you pick up the file using angular, if you want you can
check here for more details.
Here is my small example the code is in jade.
input(type="file" name="file" onchange="angular.element(this).scope().selectFile(this.files)")
button(ng-click='savePhoto()') Save
In your angular controller
$scope.savePhoto = function () {
var fd = new FormData();
fd.append("file", $scope.files[0]);
)) ;
$http.post("/xxx/photos", fd, {
withCredentials: true,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
}).success(function (data) {
$scope.image = data; // If you want to render the image after successfully uploading in your db
});
};
Install multer using npm in your back end. And then in app.js you can set up a middleware to collect the files you are sending in. Just do console.log(req) here to check if you are getting the files till here. Multer does the magic here.
app.use(multer({
dest: path.join(__dirname, 'public/assets/img/profile'),
rename: function (fieldname, filename, req, res) {
console.log(req)// you will see your image url etc.
if(req.session.user) return req.session.user.id;
}
}));
So here the image will be stored in this path (public/assets/img/profile) in your server.
Now you pick up the file from this server and add to your db.
var path = require('path');
var imgPath =path.join(__dirname, '../public/assets/img/profile/' + id + '.jpg'); // this is the path to your server where multer already has stored your image
console.log(imgPath);
var a ;
a = fs.readFileSync(imgPath);
YourSchema.findByIdAndUpdate( id, {
$set:
{'img.data' : a,
'img.contentType' : 'image/png' }
}, function(err, doc) {
if (err)console.log("oi");
}
);
//In case you want to send back the stored image from the db.
yourSchema.findById(id, function (err, doc) {
if (err)console.log(err);
var base64 = doc.img.data.toString('base64');
res.send('data:'+doc.img.contentType+';base64,' + base64);
});
In your schema store the image in type Buffer
img: { data: Buffer}

Using html2pdf with angularjs

Hey guys I'm trying to generate a pdf file using html2pdf but I couldn't succeed to make it work because I get an unreadable content
so basically what I have is a simple php page that generate a pdf file
$content = ob_get_clean();
require_once(dirname(__FILE__).'/../vendor/autoload.php');
try
{
$html2pdf = new HTML2PDF('P', 'A4', 'fr', true, 'UTF-8', 0);
$html2pdf->writeHTML($content, isset($_GET['vuehtml']));
$html2pdf->createIndex('Sommaire', 25, 12, false, true, 1);
$html2pdf->Output('bookmark.pdf');
}
catch(HTML2PDF_exception $e) {
echo $e;
exit;
}
from the other side I have my service that he sends some data to it and get the file back something like this
this.generatePDF = function (commande) {
var deferred = $q.defer();
$http({
method: 'POST',
//responseType: 'arraybuffer',
url: 'vendor/modules/html2pdf/examples/bookmark.php',
timeout: 15000,
data: $.param({'data': commande}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
//headers: {'Content-Type': 'application/pdf'}
//header :{"Content-Disposition": "attachment; filename=sample.pdf"}
}).then(function successCallback(response) {
debugger;
deferred.resolve(response.data);
}, function errorCallback(response) {
deferred.resolve(response.statusText);
});
return deferred.promise;
};
for the last part which is the controller side when the user presse generate I call my service and bind data to it and then get the whole stuff back after success and write it into the content of a new window
var popup = $window.open('', 'TEST', 'width=500,height=900');
ServiceCommande.generatePDF($scope.commande).then(function (data) {
popup.document.write(data);
});
the thing is a get some strange stuff instead of the pdf that I send
strange behavior pdf format
Thank you ^^
Try to use PhantomJS`. It has got a wide support for CSS elements.
Install it, and put the executable in system's environment PATH.
Create a file index.js. Contents of this file will be:
//create page
var page= require('webpage').create();
var system = require('system');
page.paperSize = {
format: 'A4',
orientation: 'portrait'
}
//check for number of parameters
if (system.args.length < 3) {
console.log('Usage: phantomjs index.js <web page URL> <ouptut path/filename>');
phantom.exit();
}
page.open(system.args[1], function (status) {
console.log("Status: " + status);
if (status === "success") {
page.render(system.args[2]);
}
else {
console.log("Failed")
}
phantom.exit();
});
Now fetch any webpage link, it will convert it into pdf, issuing commands as:
phantomjs index.js index.html index.pdf

Updating JSON file with AngularJS

I would like to update a JSON file using my AngularJS app.
Here is my service:
myGallery.factory('galleryData', function ($resource,$q) {
return $resource('./data/gallery.json', {}, {
update: { method: 'PUT' },
'query': { method: 'GET', isArray: true }
});
});
My controller is:
myGallery.controller('GalleryController',
function GalleryController($scope, galleryData)
{
$scope.galleries = galleryData.query();
$scope.addGallery = function (newGallery) {
$scope.galleries.push({
name: newGallery.name
});
newGallery.name = "";
};
$scope.saveGallery = function () {
$scope.saveGallery.$update();
// ???
};
});
but in the save method, I don't know what I have to do.
Any idea?
You cannot update a file just like that. You will need to write some server-side handling for that situation and update the file manually with request data.
Implementation depends on what server technology do you use.

Resources