get image file object from url - html

I am making a django-angularjs webapp.
There is a option for file uploading for the users.
I want to provide users with some sample images to upload.
So it will be like the sample images will be sent by server to client and again send back to the server if the client chooses them as Fresh upload.
angularjs directive:
angular.module('users').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]);
});
});
}
};
}]);
my html:
<input type="file" file-model="myFile"/><br><br>
<button ng-click="uploadFile()">Upload</button>
angular-js controller:
$scope.uploadFile = function(){
var file = $scope.myFile;
var uploadUrl = "/multer";
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl,fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
console.log("success!!");
})
.error(function(){
console.log("error!!");
});
};
Using the code above the user can select the image from their pc and upload them.
Now if we have the url for the sample images sent by server.
How to code the angular controller to get images for their file object from those urls?
like $scope.myFile=getImageFileObjectFromUrl(url) ??
thanks for help

$http.get("image_url", {responseType: "arraybuffer"}).success((data) => {
fd.append('file', data);
});
It's a general idea, when you get your image url, just make a request as arraybuffer to the URL, then you just have to pass the blob object to your formdata.

Convert a image from the given url into a file object:
$http.get(url,{responseType: "blob"}).success((data) => {
var file = new File([data], "sample.jpg");
$scope.sampleFile=file;
});

It also may help
$http.get(url.path, {responseType: "blob"}).then((res) => {
let fileUrl = (window.URL || window.webkitURL).createObjectURL(res.data);
resolve({file: fileUrl, type: url.type, name: url.name});
});

Related

Delete Objects in Bucket with jQuery

How do i selete an object in a bucket through a jQuery-Call. The following Code shows my example for uploading the file. The goal is to have the deleting in a similar way. Thanks
function uploadFile(node) {
$('#hiddenUploadField').click();
$('#hiddenUploadField').change(function () {
if (this.files.length == 0) return;
var file = this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
}
});
break;
}
});
}
You could expose the necessary part on the server side (just like it is done for the /api/forge/oss/objects endpoint which uploads a file to a given bucket) which then could be called from the client side in a similar way.
Server side:
router.delete('/buckets/:id', function (req, res) {
var tokenSession = new token(req.session)
var id = req.params.id
var buckets = new forgeSDK.BucketsApi();
buckets.deleteBucket(id, tokenSession.getOAuth(), tokenSession.getCredentials())
.then(function (data) {
res.json({ status: "success" })
})
.catch(function (error) {
res.status(error.statusCode).end(error.statusMessage);
})
})
Client side:
function deleteBucket(id) {
console.log("Delete bucket = " + id);
$.ajax({
url: '/dm/buckets/' + encodeURIComponent(id),
type: 'DELETE'
}).done(function (data) {
console.log(data);
if (data.status === 'success') {
$('#forgeFiles').jstree(true).refresh()
showProgress("Bucket deleted", "success")
}
}).fail(function(err) {
console.log('DELETE /dm/buckets/ call failed\n' + err.statusText);
});
}
Have a look at this sample which has both file upload and bucket deletion implemented: https://github.com/adamenagy/oss.manager-nodejs
Ah great, thank you. And how would you solve it on the server side with C# ? Rigth now the Upload on server-side looks like:
[HttpPost]
[Route("api/forge/oss/objects")]
public async Task<dynamic> UploadObject()
{
// basic input validation
HttpRequest req = HttpContext.Current.Request;
if (string.IsNullOrWhiteSpace(req.Params["bucketKey"]))
throw new System.Exception("BucketKey parameter was not provided.");
if (req.Files.Count != 1)
throw new System.Exception("Missing file to upload");
string bucketKey = req.Params["bucketKey"];
HttpPostedFile file = req.Files[0];
// save the file on the server
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"),
file.FileName);
file.SaveAs(fileSavePath);
// get the bucket...
dynamic oauth = await OAuthController.GetInternalAsync();
ObjectsApi objects = new ObjectsApi();
objects.Configuration.AccessToken = oauth.access_token;
// upload the file/object, which will create a new object
dynamic uploadedObj;
using (StreamReader streamReader = new StreamReader(fileSavePath))
{
uploadedObj = await objects.UploadObjectAsync(bucketKey,file.FileName,
(int)streamReader.BaseStream.Length, streamReader.BaseStream,"application/octet-
stream");
}
// cleanup
File.Delete(fileSavePath);
return uploadedObj;
}

How to upload blob object of type video/webm from nodejs to Mongo DB?

I have to upload video blob object to Mongo DB using NodeJS.
For video i am using video.js https://github.com/collab-project/videojs-record
I am sending blob object to NodeJS using Ajax call like below.
var file={
name:'abc',
data: player.recordedData.video
};
$.ajax({
type: 'POST',
url: '/uploadVideo',
data: file,
dataType: 'JSON'
}).done(function(data) {
alert("success");
});
Here file is JSON object i wanted to save in my collection containing other fields like file name,blob data etc. At Node.js end I have below code
router.post('/uploadVideo',function (req, res ,next) {
var file=req.body;
console.log("file"+file);
var collection = db.get('test');
collection.insert(file, function(err, result){
console.log('video saved in mongo db');
res.send(file);
});
});
Console statement in which file object is printed works fine.
But getting 500 error while inserting the JSON in mongo DB collection.
Can anyone provide me a solution for inserting blob in collection? Also let me know if my code has any bug.
Thanks
I am not sure what middleware are you using? Here is the working sample which uses multer and body-parser.
Important piece of code:-
The form data field name (uploadfile) should match. And then read the file from the downloaded location using fs and set it in the document that will be inserted into MongoDB collection.
upload.single('uploadfile');
insertdata["file"] = fs.readFileSync(req.file.path);
Form data field name:-
File upload: <input type="file" name="uploadfile"><br>
Full HTML form:-
<form action="http://localhost:3000/filesave" enctype="multipart/form-data" method="post">
Username: <input type="text" name="username"><br>
File upload: <input type="file" name="uploadfile"><br>
<input type="submit" value="Send">
</form>
Working code:-
var express = require('express');
var Db = require('mongodb').Db,
Server = require('mongodb').Server,
bodyParser = require('body-parser')
fs = require('fs');
var db = new Db('test', new Server('localhost', 27017));
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var collection, dbObj;
module.exports = {
};
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
var exports = module.exports;
app.post("/filesave", upload.single('uploadfile'), function (req, res) {
db.open(function (err, success) {
if (err) {
console.log("DB connection error");
} else {
console.log("DB connection is successful");
console.log(req.body.username);
console.log(req.file);
var insertdata ={};
insertdata["username"] = req.body.username;
insertdata["file"] = fs.readFileSync(req.file.path);
db.collection("filesave").insert(insertdata, function (inserr, result) {
if (inserr) {
console.log(inserr);
db.close(true);
res.json(inserr);
} else {
db.close(true);
res.json("Successfully persisted in database");
}
});
}
})
});
app.listen(3000);
Data saved in MongoDB collection:-

How to map URL to node.js route

I am using ui-router with Angular and Node.js as my UI server for API calls to another server. Right now, my browser URL (dynamic based on dropdown selections) does not map to the server.
For example, the browser URL is "/home?color=Red&&size=Large" when I send the user inputs to Node. When I copy and paste that URL in another browser window, I want the color and size dropdowns to already be selected as Red and Large, and results from API call based on the selections displayed. How can I accomplish this?
My AngularJS controller code:
$scope.getResults = function() {
$location.search('color', $scope.myColor);
$location.search('size', $scope.mySize);
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};
AngularJS service for the above function:
app.factory('server', ['$http', function($http){
return {
getResults : function(color, size) {
var req = {};
req.color = color;
req.size = size;
return $http({
method: 'GET',
url: 'results',
params : req
});
}
}
}]);
ui-router in Angular:
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
In Node.js, I have my route like this:
app.get("/results", function (req, res) {
var api = 'some api call/' + req.query.color + '/' + req.query.size;
request(api, function (error, response, api) {
if (!error && response.statusCode == 200) {
res.json({
Response: api
});
}
});
});
In your code you wrote query parameters but you need to read them, try this:
$scope.getResults = function() {
$scope.myColor = $location.search().color;
$scope.mySize = $location.search().size;
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};

angularJS add JSON by http request

want to download a JSON of beercat('bieres.json') in this.bieres
How could I do?
function() {
var app = angular.module('monStore', []);
app.service('dataService', function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'bieres.json'
});
}
});
app.controller('StoreController', function($scope,dataService){
this.bieres = [];
dataService.getData().then(function(dataResponse) {
$scope.bieres = dataResponse.data;
});
...
});
I think it's my access by this.bieres that it's wrong,
the Json is loaded in the console, but a blank page is in result

RESTify on Node.js POST body / json

I am in need of help. I am POSTing json data to my node server. The node server is using RESTify for its API. I am having trouble getting req.body.name from the body of the posted data.
The posted data contains a json body. In it i have keys such as name, date, address, email, etc.
I want to get the name out of the json body. I am trying to do req.body.name but it is not working.
I have also included server.use(restify.bodyParser()); and it is not working.
I am able to req.params.name and assign a value. But if I POST json data like: {'food': 'ice cream', 'drink' : 'coke'}, I am getting undefined. However, If I do req.body, I get the full json body posted. I want to be able to specifically get an item like 'drink' and have that show on console.log.
var restify = require('restify');
var server = restify.createServer({
name: 'Hello World!',
version: '1.0.0'
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.jsonp());
server.use(restify.bodyParser({ mapParams: false }));
server.post('/locations/:name', function(req, res, next){
var name_value = req.params.name;
res.contentType = 'json';
console.log(req.params.name_value);
console.log(req.body.test);
});
server.listen(8080, function () {
console.log('%s listening at %s', server.name, server.url);
});
If you want to use req.params, you should change:
server.use(restify.plugins.bodyParser({ mapParams: false }));
to use true:
server.use(restify.plugins.bodyParser({ mapParams: true }));
Have you tried using the standard JSON library to parse the body as a json object? Then, you should be able to grab whatever property you need.
var jsonBody = JSON.parse(req.body);
console.log(jsonBody.name);
In addition to below answer . The latest syntax in restify 5.0 has been change .
All the parser that you are looking for is inside restify.plugins instead of restify use restify.plugins.bodyParser
The method to use it is this.
const restify = require("restify");
global.server = restify.createServer();
server.use(restify.plugins.queryParser({
mapParams: true
}));
server.use(restify.plugins.bodyParser({
mapParams: true
}));
server.use(restify.plugins.acceptParser(server.acceptable));
var restify = require('restify')
const restifyBodyParser = require('restify-plugins').bodyParser;
function respond(req, res, next) {
console.log(req.body)
const randomParam = req.body.randomParam
res.send(randomParam);
next();
}
var server = restify.createServer();
server.use(restifyBodyParser());
server.post('/hello/:name', respond);
server.head('/hello/:name', respond);
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
});
... Is what worked for me with restify version 8.3.2
you must use req.params with bodyParser active.
var restify = require('restify');
var server = restify.createServer({
name: 'helloworld'
});
server.use(restify.bodyParser());
server.post({path: '/hello/:name'}, function(req, res, next) {
console.log(req.params);
res.send('<p>Olá</p>');
});
server.get({path: '/hello/:name', name: 'GetFoo'}, function respond(req, res, next) {
res.send({
hello: req.params.name
});
return next();
});
server.listen(8080, function() {
console.log('listening: %s', server.url);
});