How to get image from url using meteor / javascript - javascript

I am newbie user of meteor. I am using file picker apis , i can easily upload my files to there server and they give me a unique url in return . When it comes to again fetch that file its creating a problem to me .
You can tell me how to get back file using that url by using filepicker api . You can tell me how to use that url and get image , by using meteor
When i upload a picture to filepicker.io they return me a json object like following
[{"url":"https://www.filepicker.io/api/file/kIrtNvQRta7GxlFVfiP2","filename":"brazil.jpg","mimetype":"image/jpeg","size":2660,"key":"ZML3OjrFTVyV4waBzRIT_brazil.jpg","isWriteable":true}]
So how to get the image on meteor?
Thank You in advance

The normal image source should work:
<template name="image">
<img src="{{img}}"/>
</template>
and your javascript to give it the url
Template.image.img = function() {
var yourfilepickerjson = [{"url":"https://www.filepicker.io/api/file/kIrtNvQRta7GxlFVfiP2","filename":"brazil.jpg","mimetype":"image/jpeg","size":2660,"key":"ZML3OjrFTVyV4waBzRIT_brazil.jpg","isWriteable":true}]
return yourfilepickerjson[0] && yourfilepickerjson[0].url;
}
You could pass the filepickerjson via Session object so that its reflected reactively as soon as you get it

Related

display user profile image of chat sender in django-template

All is working good except of the fact that, i am trying to display user profile images of user who sent a chat message in a chat room .
this is what my image patth prints "profilepics/images_g9LwcHF.jpg".
Note i am using django framework
<script>
chatSocket.onmessage=function(e){
var tag_img=document.createElement('img');
var get_user=document.querySelector('#user').value
var tagname=document.createElement('li');
var data =JSON.parse(e.data);
document.querySelector('.img_tag').src=data.message.sender_img
</script>
Dom
<img class ="img_tag">
This is my consumer.py
messaage_json={
'user':me.username,
'message':message_object.message,
'sender':message_object.sender.username,
'sender_img':str(message_object.sender.profilepicture),
'created':str(message_object.created)
}
#coverting data to string
myResponse={
"message":messaage_json,
}
#broad cast the message event to be send
# in the layaer
await self.channel_layer.group_send(
self.room_group_name,{
# call the chat_message method
"type":"chat_message",
#covert string data to json objects
"text":json.dumps(myResponse),
}
)
It prints out the user profile image path in the media file, but cannot display the image using javascript.
Note i am using django .
I do not see you actually injecting the newly created image DOM-node into the DOM, e.g. somewhere you would need to do that for the image to be displayed:
chatSocket.onmessage=function(e){
var data =JSON.parse(e.data);
var tag_img=document.createElement('img');
tag_img.src = data.message.sender_img;
document.querySelector('.img_tag').appendChild(tag_img);
yes i solved the problem . To display the image path, since all uploaded images are stored in django media file , i am to use the following bellow
tag_img.src = '/'+'media'+'/'+ data.message.sender_img;

How to send image link from Laravel storage to frontend(angular). All work property except image

public function index(){
$data = HeaderSlider::all();
return $data;
}
<ul *ngFor="let item of data">
<img [src]="item.image" />
</ul>
How to send (Laravel) image as link to frontend(angular)
Where I store my image which sending like a response ? I try with storage in laravel but without success? I only want send link from server to frontend angular and in Angular bind src and print image. All my data from index function laravel come to frontend and all work property except image link ? Which folder in laravel is main for storage image? I try to search on google answer but I find only for request input type i don't want that.
i'm also working on angular with laravel , best approach to is to concatenate full url in laravel query with image , like ,
Website Url where you will put your laravel api address
-------------------------------------------------------
HeaderSlider::CrossJoin('websiteurl')->select(DB::raw('CONCAT("websiteurl.base_url , headerslider.image") as image'))->get()
create column as
if (!Schema::hasTable('file_attachment')) {
Schema::create('file_attachment', function (Blueprint $table) {
$table->increments('FileAttachmentID');
**$table->string('FileType')->nullable();
$table->string('FilePath')->nullable();
$table->integer('FileSourceID')->nullable();
$table->integer('SourceID')->nullable();**
//$table->dateTime('CreatedOn')->nullable();
$table->integer('CreatedBy')->nullable();
//$table->dateTime('ModifiedOn')->nullable();
$table->integer('updated_by')->nullable();
$table->timestamps();
});
}
in response send filepath in json.
if you are storing the image in laravel public directory.
if the image available in public/images/beautifulNature.jpg. Then send /images/beautifulNature.jpg as the URL to the frontend and use in your html component something like this.
<img src="{{url('/images/beautifulNature.jpg')}}" alt="Image"/>

Express JS render view with received image

I am working with two Express JS applications one is an API and second is application that is using this API by making requests and displaying received informations to user.
In API route I'm sending image as response:
router.get('/:customer_id',authController.isAuthenticated,(req,res) => {
.
. Retrieving customer data
.
return res.sendFile('/uploads/'+foundCustomer.doc_path);
});
And later another application is getting this document:
router.get('/:customer_id',(req,res) => {
var options = {
url: 'http://'+config.API.user+':'+config.API.password+'#'+config.API.host+':'+config.API.port+'/customers/'+req.params.customer_id
};
request(options,(err,response,body)=>{
return res.render('customer/show',{
document: ?, // Send document as parameter to view
});
});
});
In this point I want to render customer/show(EJS view engine) with customer document, but I don't want to save this document in my application files, because document is only needed to display in view (customer details and document are stored in another application).
I was trying to create temporary directory in my application structure, but it is difficult to manage deleting those not needed documents (Application has many users and at the same time many customers can be displayed).
Another solution that I was trying to implement is to make Ajax request on client side and latter append received document to <object data='document'>. But this request has to be authenticated with user and password, so I realised that storing credentials on client side javascript is not the best idea...
I am not sure that is it even possible to render and display image without saving in application files?
I would be grateful for any help, maybe the best workaround is to somehow manage temporarily saved documents.
Why not create a File object inside EJS template then use that for src attribute on an <img> ? You're already getting the raw buffer/blob from your image API server. Store it inside template.
From https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
// place this code (store this variable) inside of your EJS template
// so it can be used by the client-side JS
var aBlob = new Blob( array[, options]); // Where array is the raw buffer data returned from your image API server
See https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
var objectURL = URL.createObjectURL( aBlob ); // Where object is a Blob object
See https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject
const img = document.createElement('img');
img.src = objectURL;
Final solution (tested), using axios to make API request:
In my route I'm going to make HTTP request to my API to retrieve PDF file(document):
axios.get(`http://my-api/customer/id`).then(response => {
var photo = new Buffer(response.data, 'binary').toString('base64');
return res.render('customers/show',{
document: document
});
});
In my ejs view, I'm using HTML object tag to display received PDF:
<object data="data:application/pdf;base64,<%-document%>"></object>

How to set the value received from the response to .js or json file

I am using the karate api framework to automate web services.
Currently, I am facing problem to set the response value back to the .js or JSON file which I receive from the cucumber feature file.
My response:{"authorizationtoken" : "58102a8c9e074d578edae8f3d5e96001'}
How can I save this to .js or JSON file to reuse them in other scripts [feature files] ?
Thanks in advance.
You cannot save the value to a .js or JSON file provided you don't want to write the value to a json file
You can assign the value to a variable , let say using a namespacing technique to avoid collision
var nameSpaceObject = {
authKey : "",
someOtherFunctionIfNecessary :function(){}
};
Then you can call this name space & assign value to it
var response = {"authorizationtoken" : "58102a8c9e074d578edae8f3d5e96001' }
nameSpaceObject.authKey = response.authorizationtoken;

Change content of file - Alfresco

I have an Custom Document Library Action to Alfresco files, and when I press this button opens a new page with an applet (javascript) to make changes to a file, but I'm doing the modifications in base64 and to "appear" on the screen with this :
var stringPDF = "<object data=\"data:application/pdf;base64," +
JSON.parse(pdfbase64).message + "\"
type=\"application/pdf\"width=\"100%\"
height=\"100%\"></object>";$("#pdfTexto").html(stringPDF);
But I really need is to change the file, for when the repository again, there have to change, not just display. How do I change the existing file's contents to the new with the change?
I use this URL to make GET of the file:
http://localhost:8080/share/proxy/alfresco/slingshot/node/content/workspace/SpacesStore/21384098-19dc-4d3f-bcc1-9fdc647c05dc/latexexemplo.pdf
Then I convert to the base64... And I make the changes...
But if I want to make a POST to change the content, how can I make this?
Thanks in advance.
As I mentionned in my response to this question :
The fastest and easiest way to achieve that is to leverage the RESTfull API
This will also ensure compatibility with new versions of alfresco.
Note that you need to provide the noderef for the document to update in the form property updatenoderef and that the property majorversion is a boolean flag to specify if the new version is a minor/major version of the document.
Here is a sample code that might help you with your usecase:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(<alfresco-service-uri>+"/api/upload?alf_ticket="+<al-ticket>);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("username", "<username>", ContentType.TEXT_PLAIN);
builder.addTextBody("updatenoderef", <noderef>, ContentType.TEXT_PLAIN);
builder.addTextBody("...", "...", ContentType.TEXT_PLAIN);
builder.addBinaryBody("filedata", <InputStream>, ContentType.DEFAULT_BINARY, <filename>);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
JSONObject responseJson = new JSONObject(responseString);
if (response.getStatusLine().getStatusCode()!=200){
throw new Exception("Couldn't upload file to the repository, webscript response :" + responseString );
}
Note 1: You need to replace these tockens <*> with your own values/vars
Note 2: If you have problem retrieving a ticket, check this link, or this one
Note 3: To do this in JavaScript instead of java, visit this link and try to use js to post the parameters I referred as instructed !
Note 4: Since you are working on share, you are most probably authenticated.
If it is the case, you can access your alfresco repo through the proxy endpoint in share and all requests will have authentication ticket attached to them before getting forwarded to your repo !
In other terms, use this endpoint :
/share/proxy/alfresco/api/upload
Instead of :
/alfresco/service/api/upload
and You won't even have to attach a ticket to your requests.
You need to follow these steps to achieve what you are looking for.
1) Reading File:
To display content of PDF file already uploaded you need to read content of file. You are able to do it successfully using following API call.
http://localhost:8080/share/proxy/alfresco/slingshot/node/content/workspace/SpacesStore/21384098-19dc-4d3f-bcc1-9fdc647c05dc/latexexemplo.pdf
2) Capture New Content:
Capture new file content from User from applet. I guess you are storing it in some String variable.
3) Edit Existing File Content:
Issue here is that you cannot simply edit any pdf file using any of out of box Alfresco REST API (as far as I know). So you need to create your own RESTFul API which could edit pdf file's content. You can consider using some third party libraries to do this job. You need to plugin logic of editing pdf in RESTFul API
4) Changes back to Repo:
Call Your API from Step 3:
You could also have look at this plugins which could fulfill your requirements.
https://addons.alfresco.com/addons/alfresco-pdf-toolkit
Hope this helps.

Categories