Im using the following function to upload an image to our application:
const result = await ImagePicker.launchCameraAsync({
allowsEditing:true,
});
This returns the following object:
Object {
"cancelled": false,
"height": 3200,
"type": "image",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sepbaa%252Frepoflex/ImagePicker/ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg",
"width": 2400,
}
Afterwards we need to upload the image to our backend, but we don't know where the image data is. If we do a fetch to the uri from the previous object, it returns the following:
Object {
"_bodyBlob": Object {
"_data": Object {
"collector": Object {},
"blobId": "c0e241fa-9b39-4aed-9860-793a393408dd",
"lastModified": 0,
"name": "ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg",
"offset": 0,
"size": 4864483,
"type": "image/jpeg",
},
},
"_bodyInit": Object {
"_data": Object {
"collector": Object {},
"blobId": "c0e241fa-9b39-4aed-9860-793a393408dd",
"lastModified": 0,
"name": "ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg",
"offset": 0,
"size": 4864483,
"type": "image/jpeg",
},
},
"bodyUsed": true,
"headers": Object {
"map": Object {
"content-type": "image/jpeg",
},
},
"ok": false,
"status": 0,
"type": "default",
"url": "",
}
We need to send to our backend the raw image bytes. Where is that data stored? How can we retrieve it?
For uploading it to backend you need to do like this
const form = new FormData();
form.append({
name: "SampleImage.jpg", // Name of file
uri: "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sepbaa%252Frepoflex/ImagePicker/ff4dc82d-f14b-4b23-a81a-30e87c34d7e0.jpg", // URI of the file
type: "image/jpg", // MIME type of the file
})
Now you just simply have to perform a POST request with this form as body
Also in the backend you can access it like this
req.file // Depends on the backend you are using ...
Related
I get an array from the API as follows:
[ { "URL": "", "avatar": "", "characterID": 853, "creationDate": "2022-01-22T17:12:42", "description": "description", "foreignSuggestionID": 0, "id": 5, "seriesID": 0, "type": "IMAGE", "userID": 168314031248113660 } ]
However I expect
[ { "URL": "", "avatar": "", "characterID": 853, "creationDate": "2022-01-22T17:12:42", "description": "description", "foreignSuggestionID": 0, "id": 5, "seriesID": 0, "type": "IMAGE", "userID": 168314031248113664} ]
The userID gets transformed in the request by Javascript, since when I use transformResponse: data => data I get the correct ID.
This gets me to the conclusion that it cannot contain the large number in Javascript. My question here would be, is there a way to make sure that a specific value within the json array is seen as a bigint or can I convert the column into a string on receiving the response?
I use axios and my code is as follows:
this.$axios.get(url, {
withCredentials: 'true'
})
.then(response => {
this.data = response.data
})
I am trying to download the tar file in node-red.
Following is my JavaScript code to download the file.
downloadTar(sendObj).then(res => {
var bytes = new Uint8Array(byte); // pass your byte response to this constructor
var blob = new Blob([bytes], {type: "application/tar"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = 'genome.tar';
link.download = fileName;
link.click();
});
function downloadTar(data) {
return new Promise((resolve, reject) => {
$.ajax({
url: nodeRedDownloadTar,
type: 'POST',
data: data,
success: function (result) {
resolve(result);
}
});
});
}
Following is my Node-Red flow, I am reading the file in a single Buffer Object and sending it to the http response
Then following is the response I am getting it from the backend.
The problem is the tar file is not getting downloaded. I am not sure where I am making the problem.
The following flow is working properly, I'm using the headers option in the http-response node to set the content-type to appplication/x-tar
[
{
"id": "6e993a09.f44244",
"type": "file in",
"z": "1c834717.22be01",
"name": "",
"filename": "/home/pi/test.tar",
"format": "",
"chunk": false,
"sendError": false,
"encoding": "none",
"x": 600,
"y": 580,
"wires": [
[
"6e7d5f6f.c9477"
]
]
},
{
"id": "df49df3b.d325b",
"type": "http in",
"z": "1c834717.22be01",
"name": "",
"url": "/tar",
"method": "post",
"upload": false,
"swaggerDoc": "",
"x": 380,
"y": 580,
"wires": [
[
"6e993a09.f44244"
]
]
},
{
"id": "6e7d5f6f.c9477",
"type": "http response",
"z": "1c834717.22be01",
"name": "",
"statusCode": "",
"headers": {
"content-type": "application/x-tar"
},
"x": 800,
"y": 580,
"wires": []
}
]
I am relatively new to JavaScript.
I am trying to extract specific information from AWS about my EC2 instances using describeInstances. Specifically, I want to be able to provide a list of InstanceIds and extract from the resulting object the value of the Tags with Key: "Name". Here is the base code:
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Load credentials and set region from JSON file
AWS.config.loadFromPath('./.aws/config.json');
// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
var params = {
DryRun: false,
InstanceIds: ['i-0be50217a4028a044', 'i-08b83c1c428e9a1d2']
};
ec2.describeInstances(params, function(err, data) {
if (err) {
console.log("Error", err.stack);
} else {
console.log("Success", JSON.stringify(data));
}
});
Upon running this code, a large, hairy, and nested object is returned. The JSON.stringify() version of this is shown here:
{
"Reservations": [{
"ReservationId": "r-04e32387e546387ba",
"OwnerId": "543800113692",
"Groups": [],
"Instances": [{
"InstanceId": "i-08b83c1c428e9a1d2",
"ImageId": "ami-8aa998ea",
"State": {
"Code": 16,
"Name": "running"
},
"PrivateDnsName": "ip-10-77-113-210.us-west-2.compute.internal",
"PublicDnsName": "ec2-35-165-200-222.us-west-2.compute.amazonaws.com",
"StateTransitionReason": "",
"KeyName": "Security1",
"AmiLaunchIndex": 0,
"ProductCodes": [],
"InstanceType": "t2.micro",
"LaunchTime": "2017-02-14T14:59:11.000Z",
"Placement": {
"AvailabilityZone": "us-west-2b",
"GroupName": "",
"Tenancy": "default"
},
"Monitoring": {
"State": "disabled"
},
"SubnetId": "subnet-228da755",
"VpcId": "vpc-af0f0dca",
"PrivateIpAddress": "10.77.113.210",
"PublicIpAddress": "35.165.200.222",
"Architecture": "x86_64",
"RootDeviceType": "ebs",
"RootDeviceName": "/dev/sda1",
"BlockDeviceMappings": [{
"DeviceName": "/dev/sda1",
"Ebs": {
"VolumeId": "vol-00e55d6bf114bfcaa0",
"Status": "attached",
"AttachTime": "2017-02-09T15:37:34.000Z",
"DeleteOnTermination": true
}
}],
"VirtualizationType": "hvm",
"ClientToken": "vOiiS1486654656072",
"Tags": [{
"Key": "Name",
"Value": "Fenris"
}],
"SecurityGroups": [{
"GroupName": "launch-wizard-2",
"GroupId": "sg-2312072c"
}],
"SourceDestCheck": true,
"Hypervisor": "xen",
"EbsOptimized": false
}]
}, {
"ReservationId": "r-0bbcb12e5c1162c23",
"OwnerId": "543800113692",
"Groups": [],
"Instances": [{
"InstanceId": "i-0be50217a40028a044",
"ImageId": "ami-8ba011ea",
"State": {
"Code": 80,
"Name": "stopped"
},
"PrivateDnsName": "ip-10-77-118-17.us-west-2.compute.internal",
"PublicDnsName": "",
"StateTransitionReason": "User initiated (2016-12-05 16:49:45 GMT)",
"KeyName": "Security3",
"AmiLaunchIndex": 0,
"ProductCodes": [],
"InstanceType": "t2.medium",
"LaunchTime": "2016-12-02T15:50:08.000Z",
"Placement": {
"AvailabilityZone": "us-west-2b",
"GroupName": "",
"Tenancy": "default"
},
"Monitoring": {
"State": "disabled"
},
"SubnetId": "subnet-228da700",
"VpcId": "vpc-af0f1ccb",
"PrivateIpAddress": "10.77.118.17",
"StateReason": {
"Code": "Client.UserInitiatedShutdown",
"Message": "Client.UserInitiatedShutdown: User initiated shutdown"
},
"Architecture": "x86_64",
"RootDeviceType": "ebs",
"RootDeviceName": "/dev/sda1",
"BlockDeviceMappings": [{
"DeviceName": "/dev/sda1",
"Ebs": {
"VolumeId": "vol-1c211ac8",
"Status": "attached",
"AttachTime": "2016-11-22T01:54:52.000Z",
"DeleteOnTermination": true
}
}],
"VirtualizationType": "hvm",
"ClientToken": "RQbhg1479762230132",
"Tags": [{
"Key": "Name",
"Value": "Heimdall"
}, {
"Key": "Type",
"Value": "Product Dev"
}],
"SecurityGroups": [{
"GroupName": "LinuxAPIdev",
"GroupId": "sg-5ea11777"
}],
"SourceDestCheck": true,
"Hypervisor": "xen",
"EbsOptimized": false
}]
}]
}
This is way more info than I need or want. I want to find a way to get only the values of Reservations.Instances.Tags.Value from the Reservations.Instances.Tags.Name key.
I thought that just writing it that way would work. But strangely, I can't seem to access the Reservations.Instances object at all:
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Load credentials and set region from JSON file
AWS.config.loadFromPath('./.aws/config.json');
// Create EC2 service object
var ec2 = new AWS.EC2({apiVersion: '2016-11-15'});
var params = {
DryRun: false,
InstanceIds: ['i-0be5987a41191a044', 'i-08b83c3fc28e9a1d2']
};
// call EC2 to retrieve policy for selected bucket
ec2.describeInstances(params, function(err, data) {
if (err) {
console.log("Error", err.stack);
} else {
console.log("Success", JSON.stringify(data.Reservations.Instances));
}
});
This results in:
Success undefined
What am I doing wrong? How do I access the lower level of data within Instances? It is obviously there... it shows up in JSON.stringify(), but clearly I don't have the right protocol for extracting it.
(P.S. Because of AWS credentials, you won't be able to run my code without minor changes. You'll need to reference your own credentials, and InstanceIds from your own EC2 instances.)
Reservations, Instances and Tags All are arrays that''s why :
Reservations[0].Instances[0].Tags[0].Value
// value of 1ˢᵗ tag of 1ˢᵗ instance of 1ˢᵗ reservation
and Not
Reservations.Instances.Tags.Value
Within your describeInstances() method, you can simply use
// for InstanceId : "i-08b83c1c428e9a1d2"
data.Reservations[0].Instances[0].Tags[0].Value;
// and for InstanceId : "i-0be50217a40028a044"
data.Reservations[1].Instances[0].Tags[0].Value;
You can anyway create a function, if required, to return the tags value if the object structure is known.
I am having an issue traversing the objects returned from uploaded file data, but it appears that potentially the object structure that is being returned is preventing me from capturing specific properties from each of the objects in the response or that I am misinterpreting how I should be accessing this object. When I log data.length I get 995, which I assume is the number of characters in the object response. When I log data[prop] It logs each individual character.
Here is my returned file object data:
[
{
"fieldname": "fileUpload",
"originalname": "Screen Shot 2017-01-08 at 12.23.39 PM.png",
"encoding": "7bit",
"mimetype": "image/png",
"size": 39881,
"bucket": "test",
"key": "1/2017-01-23/screen-shot-2017-01-08-at-12.23.39-pm.png",
"acl": "public-read",
"contentType": "image/png",
"contentDisposition": null,
"storageClass": "STANDARD",
"metadata": null,
"location": "https://test.s3.amazonaws.com/1/2017-01-23/screen-shot-2017-01-08-at-12.23.39-pm.png",
"etag": "\"sfasgltg702o\""
},
{
"fieldname": "fileUpload",
"originalname": "Screen Shot 2017-01-08 at 12.21.04 PM.png",
"encoding": "7bit",
"mimetype": "image/png",
"size": 58386,
"bucket": "test",
"key": "1/2017-01-23/screen-shot-2017-01-08-at-12.21.04-pm.png",
"acl": "public-read",
"contentType": "image/png",
"contentDisposition": null,
"storageClass": "STANDARD",
"metadata": null,
"location": "https://test.s3.amazonaws.com/1/2017-01-23/screen-shot-2017-01-08-at-12.21.04-pm.png",
"etag": "\"151353j53j51u5j135ju\""
}
]
jQuery AJAX POST request uploading the files and returning the objects to data:
$.ajax({
url: '/app/sign',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('upload successful! ' + data);
console.log('Just the key ' + data.length);
for(var prop in data){
console.log(data[prop]);
}
},
error: function(error){
console.log('error ' + JSON.stringify(error));
}
});
data is a JSON string, you have to parse it back to an array of objects using JSON.parse like this:
success: function(data){
var arr = JSON.parse(data);
// use arr as array
console.log(arr.length);
// arr[0] is the first object
}
It's just a string in JSON format. You need either JSON.parse to convert to a JS object, or use $.getJSON().
Let's say you want to access the first fieldname, you can access it this way data[0].fieldname. The same goes for the second: data[1].fieldname. Why ? because your data is interpreted like this:
0: {"fieldname": "fileUpload", ...}, 1: {"fieldname": "fileUpload", ...}
Note: I am inexperienced with APIs, JSON, REST, etc.
I am trying to implement FilePreviews into my site. Its purpose is to take the url for any file type and convert it into a JPG or PNG.
JavaScript
var previews = new FilePreviews({
debug: true,
apiKey: 'MY_API_KEY'
});
var url = 'http://i.imgur.com/HQB8wtI.jpg';
var options = {
size: {
width: 100,
height: 999
},
metadata: ['exif', 'ocr', 'psd'],
format: 'jpg'
};
previews.generate(url, options);
The request is received by the developer's app. The following results are shown in the site dashboard of the developer's app:
{
"preview": {
"resized": true,
"size": {
"height": "178",
"width": "100"
},
"page": 1,
"url": "https://s3-us-west-2.amazonaws.com/[removed for privacy]/ec210ecf45d9d190539a241462c621f75adf2d4f835fb394a8d738d09fd412d6/HQB8wtI_100x999_1.jpg",
"requested_size": "100x999",
"original_size": {
"height": "1024",
"width": "576"
}
},
"id": "25841aca-e176-4cf7-ac1d-b01ce604a765",
"user_data": null,
"status": "success",
"url": "https://api.filepreviews.io/v2/previews/25841aca-e176-4cf7-ac1d-b01ce604a765/",
"thumbnails": [
{
"resized": true,
"size": {
"height": "178",
"width": "100"
},
"page": 1,
"url": "https://s3-us-west-2.amazonaws.com/[removed for privacy]/ec210ecf45d9d190539a241462c621f75adf2d4f835fb394a8d738d09fd412d6/HQB8wtI_100x999_1.jpg",
"requested_size": "100x999",
"original_size": {
"height": "1024",
"width": "576"
}
}
],
"original_file": {
"metadata": {
"ocr": null,
"psd": null,
"exif": null
},
"size": 82022,
"extension": "jpg",
"total_pages": 1,
"encoding": "binary",
"name": "HQB8wtI",
"mimetype": "image/jpeg",
"type": "image"
}
}
My question is: How do I get the url for the file preview into my site? Each file is referenced dynamically and there will be many on a page for most areas of my site. There seems to be no consistency in how FilePreviews is generating the folder on AWS S3, so I can't even use a clever PHP fix to solve it.
Anyone care to assist and show me the ways of this programming world?
I don't have experience with FilePreviews, but this is how I expect it should work.
First, you add an image tag in your HTML, at the spot where you want the thumbnail to appear. Give it an id, for example "thumb":
<img id="thumb"/>
Then, modify the last line of your script as follows:
previews.generate(url, options, onPreviewReceived);
The third parameter is a callback function we must define elsewhere in the script. I have called it onPreviewReceived, but you can choose your own name. It is called when the result is received. You can define the callback function as follows:
function onPreviewReceived(err, result) {
if (!err) {
var thumbnailUrl = result.thumbnails[0].url; // but see assumption
document.getElementById("thumb").setAttribute("src", thumbnailUrl);
}
}
This function assigns the url, obtained from the result, to the src attribute of the img tag.
Assumption: I expect the 'result' to be as described in your question. However, the client library documentation indicates that you will get a different result and that you should have a thumbnailUrl assignment like this:
var thumbnailUrl = result.previewUrl;
So please try that as well.