React-native-android - How to save an image to the Android file system and view in the phone's 'Gallery' - filesystems

Is it possible to save an image to the android's local file system so it can be viewed from the phone's 'Gallery' and in a folder??
I found this react-native-fs library but after studying the documentation and working through an example I am still unsure if it is possible.
Thanks

For anyone having the same problem, here is the solution.
Solution
I am using the File System API from the react-native-fetch-blob library. This is because I tought it was way better documented and easier to understand than the 'react-native-fs' library.
I request an image from the server, receive a base64 and I then save it to the Pictures directory in the android fs.
I save the image like this:
var RNFetchBlob = require('react-native-fetch-blob').default;
const PictureDir = RNFetchBlob.fs.dirs.PictureDir;
getImageAttachment: function(uri_attachment, filename_attachment, mimetype_attachment) {
return new Promise((RESOLVE, REJECT) => {
// Fetch attachment
RNFetchBlob.fetch('GET', config.apiRoot+'/app/'+uri_attachment)
.then((response) => {
let base64Str = response.data;
let imageLocation = PictureDir+'/'+filename_attachment;
//Save image
fs.writeFile(imageLocation, base64Str, 'base64');
console.log("FILE CREATED!!")
RNFetchBlob.fs.scanFile([ { path : imageLocation, mime : mimetype_attachment } ])
.then(() => {
console.log("scan file success")
})
.catch((err) => {
console.log("scan file error")
})
}).catch((error) => {
// error handling
console.log("Error:", error)
});
},
The following code that is in the above method refreshes the Gallery otherwise the images would not display untill the phone is turned off and back on again.
RNFetchBlob.fs.scanFile([ { path : imageLocation, mime : mimetype_attachment } ])
.then(() => {
console.log("scan file success")
})
.catch((err) => {
console.log("scan file error")
})
Enjoy!

You can absolutely do this with react-native-fs. There's a PicturesDirectoryPath constant which isn't mentioned in the README for the project; if you save a file into there it should appear in the Gallery app. If you want it to appear in your own album, just make a new directory in that folder and save the file into there, eg
const myAlbumPath = RNFS.PicturesDirectoryPath + '/My Album'
RNFS.mkdir(myAlbumPath)
.then(/* write/copy/download your image file into myAlbumPath here */)
I don't have full example code anymore sorry, because I ended storing images in my app's private cache directory instead. Hope this helps anyway!

Related

Firebase Storage not displaying image properly (shows a small box)

EDIT: I've updated the CORS config but its still showing the same error.
I have a Tinymce RTE on my page, and when u drop an image into the editor, I have some functions that upload it to firebase storage, then swaps out the src of the text editor with the url fetched from firebase. It works kinda ok, but its being displayed as a broken link image icon.
When I check the link, its because originally it downloads the image when the link is clicked. I added a metadata property when it uploads it, but now its just showing a tiny box.
Here is the code where the image dropped into the editor is uploaded into firebase storage
const imagesUploadHandler = async (blobInfo, success, failure) => {
try {
const file = blobInfo.blob();
const storageRef = ref(storage, file.name);
const metadata = {
contentType: 'image/jpeg',
};
await uploadBytes(storageRef, file, metadata);
const url = await getDownloadURL(storageRef);
console.log(url);
return url;
} catch (error) {
// Call the failure callback with the error message
console.log(error.message);
}
};
Originally, i didnt include the contentType metadata, and it was just uploading as application/octet-stream, which i assume is why it prompts you to save the image.
Image link: https://firebasestorage.googleapis.com/v0/b/cloudnoise-news.appspot.com/o/ref.jpg?alt=media&token=1edc90e7-1668-4a06-92a3-965ce275798b
Currently its displaying this
Somethings i checked through
firebase storage rules is in test mode, so should be able to read and write by anyone.
i tried sticking in different MIME types but it either shows the tiny box, or it shows "undefined"
the files upload successfully and the "swap" in Tinymce editor is also all good.
Any idea why this is happening?
you need to set the metadata tag
const metadata = {
contentType: file.type,
};
This should ensure that the correct content type is set when the image is uploaded to Firebase Storage.
If this does not resolve the issue, you may need to check that the URL returned from getDownloadURL is valid and points to the correct image. You can try opening the URL in a new browser tab to verify that the image is accessible.
I fixed it by adding a blob, I created a blob object with the file data, then i just made it upload the blob object instead of the single file.
const imagesUploadHandler = async (blobInfo, success, failure) => {
try {
const file = blobInfo.blob();
const storageRef = ref(storage, file.name);
const metadata = {
contentType: file.type,
};
// Create a new Blob object with the file data
const blob2 = await new Blob([file], { type: file.type });
// Upload the Blob to Firebase Storage
await uploadBytes(storageRef, blob2, metadata);
const url = await getDownloadURL(storageRef);
console.log(url);
return url;
} catch (error) {
// Call the failure callback with the error message;;
console.log(error.message)
}
};

React-Flask download excel file with button click

I'm trying to download an excel file with the click of a button in my web application. I can see the data come across from my api request, but when I download the file and try to open it I either get a:
"We found a problem with some content in ... Do you want us to try to recover as much as possible" YES => "This file is corrupt and cannot be opened"
or
"... the file format or file extension is not valid. Verify that theh file has not been corrupted..."
If I open the original file saved it works fine so it's not the file. I think the problem is somewhere in the React Code.
I've looked at a lot of other questions on Stack Overflow about this same topic but none of the answers seem to be working for me.
React
React.useEffect(() => {
if (template && downloadBtn.current != null) {
axios
.get<Blob>(
`/template`,
{ params: { filename: template } }
// responseType: 'blob' or "arraybuffer" don't work for me
)
.then((resp) => {
console.log(resp.data);
var blob = new Blob([resp.data], {
type: resp.headers['content-type'] // tried keeping and removing this
}); // removing this assuming resp.data is already a blob didn't work
console.log(blob); // PK ... b���C���h����ؒ )���G+N�
const url = window.URL.createObjectURL(blob);
console.log(url); // blob:http://localhost:3000/29fd5f64-da6a-4b9c-b4a4-76cce1d691c8
if (downloadBtn.current != null) {
downloadBtn.current.download = template;
downloadBtn.current.href = url;
}
});
}
}, [template, downloadBtn.current]);
Flask
#app.route('/template', methods=['GET'])
def template():
filename = getRouteData(['filename']) # helper function I wrote to get request.body data
print(os.path.join(
app.config['templates_folder'], filename), file=sys.stderr)
return send_file(os.path.join(app.config['templates_folder'], filename))
# adding as_attachment=True doesn't work for me either
# file path is correct

upload image to S3 presigned url using react-native-image-picker and axios

I am trying to get an presigned url image upload working correctly. Currently the upload succeeds when selecting an image from the IOS simulator, however when I actually try to view the file it seems the file is corrupted and will not open as an image. I suspect it has something to do with my FormData but not sure.
export async function receiptUpload(file) {
const date = new Date();
const headers = await getAWSHeaders();
const presignUrl = await request.post(
urls.fileUpload.presignUpload,
{file_name: `${date.getTime()}.jpg`},
{headers}
)
.then(res => res.data);
const formData = new FormData();
formData.append('file', {
name: `${date.getTime()}.jpg`,
uri: file.uri,
type: file.type
});
const fileUpload = presignUrl.presignUrl && await request.put(
presignUrl.presignUrl,
formData
)
.then(res => res.status === 200);
}
I have tried from other fixes to change the file uri like so...
Platform.OS === 'android' ? file.uri : file.uri.replace('file://', '');
however this does not seem to work either.
I did this just recently in my current project and the following code is a working example for my use case. I didn't need to convert to a blob either though I am uploading to AWS S3 so if you are uploading elsewhere that may be the issue.
export const uploadMedia = async (fileData, s3Data, setUploadProgress = () => {}) => {
let sendData = { ...fileData };
sendData.data.type = sendData.type;
let formData = new FormData();
formData.append('key', s3Data.s3Key);
formData.append('Content-Type', fileData.type);
formData.append('AWSAccessKeyId', s3Data.awsAccessKey);
formData.append('acl', 'public-read');
formData.append('policy', s3Data.s3Policy);
formData.append('signature', s3Data.s3Signature);
formData.append('file', sendData.data);
return axios({
method: 'POST',
url: `https://${s3Data.s3Bucket}.s3.amazonaws.com/`,
data: formData,
onUploadProgress: progressEvent => {
let percentCompleted = Math.floor((progressEvent.loaded * 100) / progressEvent.total)
setUploadProgress(percentCompleted);
}
})
}
I would first check to see where the issue is occurring. After uploading can you view it on whatever storage service you are trying to upload it to. If so it's something on React Native side. If it doesn't ever get uploaded to the location you know its an error in your upload process. Might help you track the exact location of the error.
I had to do this recently for a project. I believe the data is a base64 string when coming directly from the file input. So the issue is your are uploading a base64 string not the image by simply passing the data field. I had to process it before uploading to the signed URL with the following method.
private dataUriToBlob(dataUri) {
const binary = atob(dataUri.split(',')[1]);
const array = [];
for (let i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], { type: 'image/jpeg' });
}
This answer fixed it for me: How can I upload image directly on Amazon S3 in React Native?
I had tried uploading with axios and fetch with FormData. The download went through but the image file was not readable, even when downloaded to my Mac from the S3 console:
The file "yourfile.jpg" could not be opened. It may be damaged or use a file format that Preview doesn’t recognize.
Only after trying to upload with XHR with the correct Content-Type header did it work. Your signedUrl should be correct as well, which seems to be the case if the download goes through.

Where is the Ionic/Cordova dataDirectory folder?

I'm building an Ionic app using the Ionic Native File plugin. I need the app to be able to read a file that I've saved in the app itself, but I don't understand where I need to store the file. The official Cordova documentation says something about a certain cordova.file.dataDirectory, whereas the Ionic documentation uses this example:
import { File } from '#ionic-native/file';
constructor(private file: File) { }
...
this.file.checkDir(this.file.dataDirectory, 'mydir').then( //stuff).catch( //stuff);
I don't understand where I need to put my file so that the app can read them.
Do not use file:///android_asset/
You can store the file in file.dataDirectory
Storing the file
I am using http to download a zip. I then unzip and delete the zipped file afterwards.
const down = this.http.downloadFile(uri, {}, {}, path + 'data.zip')
.then(data => {
console.log(data.status);
console.log("DOWNLOAD SUCCESS");
this.desc = "Extracting";
this.loading = 100;
this.downloading = false;
this.zip.unzip(path + 'data.zip', path, (this.UnzipProgress))
.then((result) => {
if(result === 0) this.file.removeFile(path,'data.zip');
if(result === -1) console.log('UNZIP FAILED');
});
})
.catch(error => {
console.log("ERROR::");
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
Retrieving the file
The only thing that worked for me was convertFileSrc()
let win: any = window;
let safeURL = win.Ionic.WebView.convertFileSrc(this.file.dataDirectory+'data/yourFile.png');
Hope this helps

React native share image

I am trying to share an image, either taken from camera or from gallery, to other devices through various available device's application's(eg whatsApp, skype, email etc.)
I found the "Share" function provided but as per my knowledge and research, it only allows to share text data.
Has someone have any idea for sharing an image through a react native application.
Thanks in advance.
Solution:
Get the path of the image to convert base64.
For share image use: react-native-share lib share
To access the device directories, I recommend using: rn-fetch-blob.
Wikki lib
dwFile(file_url) {
let imagePath = null;
RNFetchBlob.config({
fileCache: true
})
.fetch("GET", file_url)
// the image is now dowloaded to device's storage
.then(resp => {
// the image path you can use it directly with Image component
imagePath = resp.path();
return resp.readFile("base64");
})
.then(async base64Data => {
var base64Data = `data:image/png;base64,` + base64Data;
// here's base64 encoded image
await Share.open({ url: base64Data });
// remove the file from storage
return fs.unlink(imagePath);
});
}
Hope this helps.
You can also send the image with Share through the url parameter:
url: "data:image/png;base64,<base64_data>"
Cheers
Since Expo's SDK33, you can use Expo Sharing to share any type of file to other apps that can handle its file type even if you're on Android. Without detaching or anything.
See https://docs.expo.io/versions/latest/sdk/sharing/
Usage is pretty simple:
import * as Sharing from 'expo-sharing'; // Import the library
Sharing.shareAsync(url) // And share your file !
I used react-native-share plugin to do the same
Steps :
npm install react-native-share --save
react-native link
Read here for rest of the code ...its very easy and straight forward.
If you want to share image in base64 u have to pass like this :
"data:image/png;base64,BASE STRING"
And If you want to share directly from source you have to pass like this :
url: "file://<file_path>",
Hope this helps :)
I tried as following:
import {
Share
} from 'react-native';
let shareImage = {
title: caption,//string
message: message,//string
url:imageUrl,// eg.'http://img.gemejo.com/product/8c/099/cf53b3a6008136ef0882197d5f5.jpg',
};
Share.open(shareImage).catch(err => console.log(err));
Hope this will help you.Cheers!
You cannot share both image and url simultaneously on most of the social media or platform. To do so, you will need a sharable image link that is can be created by API.
Share.share({
message: "dummy text",
url:"https://xyz.jpg"
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
})
Try this code, this should work
Fresh answer from 2022 :) Example with screenshot.
Btw, parameter url works in Android
import ViewShot,{captureScreen} from 'react-native-view-shot';
import Share from 'react-native-share';
<Pressable onPress={()=>{
captureScreen({format: "jpg",quality: 0.8,
}).then((uri) => { ShareScreenShot(uri); },
(error) => console.error("Oops, snapshot failed", error));}} >
const ShareScreenShot = async (urifile) => {
Share.open({message:'Result', url:urifile}) .then((res) => {
//console.log(res);
}) .catch((err) => {
/*err && */console.log('error', err);
});
}

Resources