Delete an image from Cloudinary using REST full api - cloudinary

How can I delete an image from my cloudinary server using simple REST api? though I'm able to upload an image successfully but couldn't find a proper way to delete the same using api

If you're using one of the Cloudinary server-side SDKs then you can delete a resource from Cloudinary using the destroy method of the Upload API.
If you're making a direct call to the API then you can use cURL. For example, to delete the image with public_id sample_image from cloud my_cloud I can do the following.
Export all required variables:
export CLD_NAME=my_cloud
export CLD_API_KEY=12345
export CLD_API_SECRET=abcde
Generate the signature:
export TIME=$(date +%s)
export SIGNATURE=$(echo -n "invalidate=true&public_id=sample_image&timestamp=$TIME$CLD_API_SECRET" | openssl sha1)
curl -X POST https://api.cloudinary.com/v1_1/$CLD_NAME/image/destroy --data "invalidate=true&public_id=sample_image&timestamp=$TIME&signature=$SIGNATURE&api_key=$CLD_API_KEY"
For more information regarding direct API calls please see this section of the documentation - https://cloudinary.com/documentation/upload_images#generating_authentication_signatures

When you upload the image,public_id shoud be saved in the database. Otherwise, you can't delete images using URL. I tried in React Js to upload images.
``
onClickHandler = () => {
const data = new FormData()
for(var x = 0; x<this.state.selectedFile.length; x++) {
data.append('file', this.state.selectedFile[x])
data.append("upload_preset","*****")
data.append("cloud_name","*****")
axios.post("https://api.cloudinary.com/v1_1/*****/image/upload",data)
.then((res) => {
console.log(res.data);
console.log(res.data);
const imageDetails={
image:res.data.secure_url,
public_id:res.data.public_id,
productName:"*******"
}
axios.post("http://localhost:4000/*********",imageDetails)
.then(res=>console.log(res))
})
}
``
Then you can delete images using node js. refer the below link to get node js code
Delete cloudinary images in node js

Related

In which stage should I generate signed urls to load S3 bucket objects in an app?

I am using S3 to store images in my app.
This is the function that generates the signed url that the user can use to upload an image:
const key = `images/${Date.now()}.jpeg`;
s3_config
.getImageSignedUrl(key)
.then((url) => {
res.status(200).send({ key, url });
})
.catch((error) => {
res.status(500).send({
message: "There was an error generating pre-signed url.",
});
});
So after the image is uploaded, the image url will look like this:
https://BUCKET_NAME.s3.amazonaws.com/images/1667119739573.jpeg
Now, in order to make the images only accessible on the website, I will also use a signed-url.
This way when someone uses the direct link:
https://BUCKET_NAME.s3.amazonaws.com/images/1667119739573.jpeg
He will get AccessDenied error.
And only users within the app, will be able to access the images using the signed urls.
This is how I generated the signed url for loading an image:
var getImageReadSignedUrl = async function (key) {
return new Promise((resolve, reject) => {
s3.getSignedUrl(
"getObject",
{
Bucket: AWS_BUCKET_NAME,
Key: key,
Expires: 300,
},
(err, url) => {
if (err) {
reject(err);
} else {
resolve(url);
}
}
);
});
};
And if I feed it an image key:
getImageReadSignedUrl("images/1667119739573.jpeg");
It will generate a signed url that will allow the user to access the private image:
https://BUCKET_NAME.s3.eu-west-3.amazonaws.com/images/1667119739573.jpeg?X-Amz-Algorithm=xxxxxxxxxxxxxxxxx&X-Amz-Credential=xxxxxxxxxxxxxxxxxxxx9%2Feu-xxxx-3%2Fs3%2Faws4_request&X-Amz-Date=202211xxxxxxxx35Z&X-Amz-Expires=300&X-Amz-Signature=5ab0exxxxxxxxxxxxxxxxxx8dc401dc7fxxxxxxxxa5124&X-Amz-SignedHeaders=host
Now, so far so good. Everything works perfectly as intended.
My problem is when or how or where exactly I should use the function getImageReadSignedUrl.
Since in the database, I am saving the direct link to the image:
https://BUCKET_NAME.s3.amazonaws.com/images/1667119739573.jpeg
When the user is using the app, he will receive that url.
And it will be using inside the img html tag, to render the image.
Now, the question is, should I use getImageReadSignedUrl everytime before there's an image url in the data that's sent back to the user and send the signed url instead?
Even though, this makes sense, this means that I will have to go through the entire app in the backend and call that function, everytime there's an image to be sent back to the user.
Is there another approach that makes more sense and is not as tedious as this?
FYI, I am using the MERN stack and an EC2 instance.
Thank you.

Apollo federation file upload

I have a problem in uploading file in apollo federation subgraph, this is my code in apollo gateway
import {
ApolloGateway,
// RemoteGraphQLDataSource //replace by FileUploadDataSource from #profusion/apollo-federation-upload for file upload
} from '#apollo/gateway'
import FileUploadDataSource from '#profusion/apollo-federation-upload'
const gateway = new ApolloGateway({ //RemoteGraphQLDataSource
serviceList, //port:4010
buildService: ({ url }) => new FileUploadDataSource({
url, useChunkedTransfer: true }),
useChunkedTransfer: true,
})
In using RemoteGraphQLDataSource from #apollo/gateway this the result of file upload
the error is BadRequestError: Missing multipart field ‘operations’.
but when I am directing the request from the service list, the file is uploaded
upon searching for it I find this solution https://www.npmjs.com/package/#profusion/apollo-federation-upload then replace RemoteGraphQLDataSource to FileUploadDataSource but the output is the same
can anybody help me about this? thank you
I solve it by setting uploads:false since I am using apollo 2 in this set up
https://github.com/profusion/apollo-federation-file-upload/issues/35

Revert or remove file with FilePond on REST API with dynamic url for uploaded image

This is regarding Filepond & Vue-adapter.
I have a struggle with revert / remove file after it has been uploaded. I run a PHP backend with OpenAPI 3 REST API standard and I need/want to use a dynamic url when revert/delete. I use Vue-adapter.
I use this method to return the uuid after file has been uploade to my example.com/media
process: {
onload: response => {
return JSON.parse(response)['#id']
},
If i use the revert: '/' way to remove, it will send the id as body to /media/, but I need to send it do DELETE /media/uniqueFileId route. I tried some ways with revert and remove but didnt manage to get it to be dynamic. If i use revert as a function, am i supposed to use axios or fetch to make a custom request to my endpoint or is there some other way im missing?
revert: (uniqueFileId, load, error) => {
console.log(uniqueFileId)
error('problems')
load()
}

React-native: download and unzip large language file

A multilingual react-native app. Each language bundle is ~50MB. It doesn't make sense to include all of them in a bundle. So, what do I do about it?
I assume the right way to go here is to download the respective language files upon language selection.
What do I do with it next? Do I suppose to store it using AsyncStorage or what?
Briefly explaining, you will:
Store JSON as ZIP in Google Storage (save memory/bandwidth/time)
Unzip file to JSON (in RN)
Store JSON in AsyncStorage (in RN)
Retrieve from AsyncStorage (in RN)
[Dependencies Summary] You can do this, using these deps:
react-native
react-native-async-storage
rn-fetch-blob
react-native-zip-archive
Tip: Always store big language json in zip format (this can save up to 90% of size).
I made a quick test here: one 3.52MB json file, turned out a 26KB zipped file!
Let's consider that yours stored zip file, can be accessed by using a public url, eg: https://storage.googleapis.com/bucket/folder/lang-file.zip.
Install and link all above RN deps, it's required to get this working.
Import the deps
import RNFetchBlob from 'rn-fetch-blob';
import { unzip } from 'react-native-zip-archive';
import AsyncStorage from '#react-native-community/async-storage';
Download the file using rn-fetch-blob. This can be done using:
RNFetchBlob
.config({
// add this option that makes response data to be stored as a file,
// this is much more performant.
fileCache : true,
})
.fetch('GET', 'http://www.example.com/file/example.zip', {
//some headers ..
})
.then((res) => {
// the temp file path
console.log('The file saved to ', res.path())
// Unzip will be called here!
unzipDownloadFile(res.path(), (jsonFilePath) => {
// Let's store this json.
storeJSONtoAsyncStorage(jsonFilePath);
// Done!
// Now you can read the AsyncStorage everytime you need (using function bellow).
});
});
[function] Unzip the downloaded file, using react-native-zip-archive:
function unzipDownloadFile(target, cb) {
const targetPath = target;
const sourcePath = `${target}.json`;
const charset = 'UTF-8';
unzip(sourcePath, targetPath, charset)
.then((path) => {
console.log(`unzip completed at ${path}`)
return cb(path);
})
.catch((error) => {
console.error(error)
});
}
[function] Store JSON in AsyncStorage:
function storeJSONtoAsyncStorage (path) {
RNFetchBlob.fs.readFile(path, 'utf-8')
.then((data) => {
AsyncStorage.setItem('myJSON', data);
});
}
Retrieve JSON data from AsyncStorage (everytime you want):
AsyncStorage.getItem('myJSON', (err, json) => {
if (err) {
console.log(err);
} else {
const myJSON = JSON.parse(json);
// ... do what you need with you json lang file here...
}
})
That's enough to get dynamic json lang files working in React Native.
I'm using this approach to give a similar feature to my i18n'ed project.
Yes you are right to make the translation file downloadable.
You can store the downloaded file in the document directory of your app.
After that you can use a package to load the translations. For instance
https://github.com/fnando/i18n-js.
I would also suggest taking a look at the i18n library which is a standard tool for internationalisation in JavaScript.
Consider taking a look at this documentations page where you can find an option of loading a translation bundle or setting up a backend provider and hooking into it.
Also, to answer the storage question, if you do not plan on setting up a backend: AsyncStorage would be an appropriate place to store your key - translation text pairs.

Local storage solutions for large data including images on React Native

Here's the flow of how my end-product should work:
When the user opens the app for the first time, fetch all the data
i.e., including images(150+) and relevant JSON objects.
On opening the app subsequently, the images and data should load
from local storage i.e., no need for internet at all.
I know it seems weird but this is my use case:
The product is a Wayfinder running on Android Box(55-inch touchscreen TV ) which will be placed in the shopping mall. It will not have access to the internet unless I manually connect it.
Hence it should load the data when opening for the first time i.e. when I'm configuring the application.
Solutions I have come across:
Realm: Local database management with excellent support for react-native - my option right now
Native Async Storage: Not suitable for large data
SQLite: Not comfortable with SQL queries
I'm still looking for options on how differently this problem can be tackled. Also, I'm familiar with Redux.
Thanks.
Check out react-native-fs (or expo-file-system if working with expo).
It is specially designed to store files on the device. In your component, it would look something like this:
const RNFS = require('react-native-fs');
RNFS
.downloadFile({ fromUrl: myURL, toFile: myFilePath })
.promise
.then(res => console.log('Done'));
use pouchDB database , this is work with indexDB local browser database
call XHR request for image and convert response to binary data and store in local database
when need to preview image , get from database and make a blobUrl and show in img tag
axios.get(url, {
progress: false, responseType: 'arraybuffer',
onDownloadProgress: (progressEvent) => {
precent = (100 * progressEvent.loaded / progressEvent.total)
console.log(precent)
}
})
.then(resp => {
//get db
let db = $db.dbModel
//set attach
db.get(doc._id).then((doc) => {
db.putAttachment(doc._id, 'index.mp4', doc._rev, new Blob([new Uint8Array(resp.data)], {type: 'video/mp4'}), 'video/mp4')
.then(res => {
// console.log('success store file')
})
})
})
https://github.com/mohammadnazari110/pwa_offline_video_download