Im trying to share a file with Navigator.Share(), in android works perfect, but in ios don't work. I can share text but not images. Exist alternativees, or i cant share files in ios?
fetch(text)
.then(function(response) {
return response.blob()
})
.then(function(blob) {
var file = new File([blob], "image.png", {type: blob.type});
var filesArray = [file];
var shareData = { files: filesArray };
navigator.share({
url: 'https://cdn.shopify.com/s/files/1/0003/6270/9002/files/toshare-05.png?v=1621420555',
});
console.log("Your system doesn't support sharing files.");
});
}
}
Related
I am trying to run a WebApp which allows files sharing.
After few google search, I found Web Share API like the standard to do so.
According to the documentation it should works like this using plain JS
This is the code for html page
<p><button>Share MDN!</button></p>
<p class="result"></p>
The code to share all sort "textbased" metadata:
let shareData = {
title: 'MDN',
text: 'Learn web development on MDN!',
url: 'https://developer.mozilla.org',
}
const resultPara = document.querySelector('.result');
if (!navigator.canShare) {
resultPara.textContent = 'navigator.canShare() not supported.';
}
else if (navigator.canShare(shareData)) {
resultPara.textContent = 'navigator.canShare() supported. We can use navigator.share() to send the data.';
} else {
resultPara.textContent = 'Specified data cannot be shared.';
}
The code above works fine, the trouble happens when I try to share files.
According to the documentation it should works like this:
// filesArray is an array of files we want to share (audios, images, videos, pdf)
if (navigator.canShare && navigator.canShare({ files: filesArray })) {
navigator.share({
files: filesArray,
title: 'Pictures',
text: 'Our Pictures.',
})
.then(() => console.log('Share was successful.'))
.catch((error) => console.log('Sharing failed', error));
} else {
console.log(`Your system doesn't support sharing files.`);
}
I started my code from this example and I never success to share a file.
My actual code using React and Typescript looks like this:
//some react code here
const shareNow = async () => {
let imageResponse = await window.fetch('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png', {mode: "no-cors"});
let imageBuffer = await imageResponse.arrayBuffer();
let fileArray = [new File([imageBuffer], "File Name", {
type: "image/png",
lastModified: Date.now()
})];
if (navigator.canShare && navigator.canShare({ files: filesArray })) {
navigator.share({
files: filesArray
}).then(() => {
console.log('Thanks for sharing!');
})
.catch(console.error);
}
}
//some react code here too
At this point, my typescript compiler yell at me.
Apparently, the navigator object has no method canShare()
I am new to typescript, but I don't understand how and why the navigator could have less attribute since TypeScript is JavaScript superset.
Anyone has an idea on how to solve that except running normal JS ?
Thank you for your time reading this, and I hope to thank you for your answers.
P.S: I also tried a react-component based solution, but all the component I found in open source which wraps Web Share API does not allow file sharing.
Edit
Hey, #DenverCoder9
There is the same use case but using vanilla JS, could anyone try it and tell me what I am doing wrong please ?
<html>
<head>
<title>Sharing Image</title>
<meta charset="UTF-8" />
</head>
<body>
<div className="App">
<img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
<button id="button">Share</button>
</div>
</body>
<script>
async function shareImage(title, imageUrl) {
const image = await fetch(imageUrl, {mode: "no-cors"});
const blob = await image.blob();
const file = new File([blob], title, { type: 'image/png' });
const filesArray = [file];
const shareData = {
files : filesArray
}
// add it to the shareData
const navigator = window.navigator
const canShare = navigator.canShare && navigator.canShare(shareData) //navigator.canShare()navigator.share //navigator.canShare()
if(canShare){
navigator.share(shareData)
.then(() => console.log('Successful share'))
.catch((error) => console.log('Error sharing', error));
}
else {
console.log("cannot share this file in this context")
}
}
document.getElementById('button').onclick = function() {
shareImage("Title", "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png")
};
</script>
</html>
I am running this on safari for mac
This is more of a TypeScript issue than a coding issue. Support for the Web Share API (Level 2) was added in this PR, so you can either update to a version of TypeScript that includes this, or alternatively teach your current TypeScript version the relevant types as follows:
type ShareData = {
title? : string;
text? : string;
url? : string;
files?: ReadonlyArray<File>;
};
interface Navigator
{
share? : (data? : ShareData) => Promise<void>;
canShare?: (data?: ShareData) => boolean;
}
I'm trying to upload images with Vue Js, but it didn't work.
If you examine the codes below, you will see that I cannot transfer the file correctly. I couldn't find where the problem originated.
I am requesting your support.
// HTML code
// There is a problem in the image or file upload area to the card.
<input type="file" v-model="cardContent.cardContentImgPath" #change="onFileChange">
// Vuejs code
onFileChange(e) {
var files = e.target.files || e.dataTransfer.files;
console.log(e.target.files);
if (!files.length)
return;
this.addToCardContent(files[0]);
},
addToCardContent: function(file){
let formData = app.toFormData(app.cardContent, file);
axios.post('https://example.com/note/api_card.php?action=addContent',formData, {
header:{
'Content-Type' : 'multipart/form-data'
}})
.then(function(response){
if(!response.data.error){
app.getListCardContent();
console.log(app.cardContent.cardContentImgPath);
app.cardContent = {cardContentText : '', cardContentImgPath : ''};
}
});
}
I am trying to download a file from the server and using Blob to display this file in a new tab, but the AdBlock extension is blocking the browser.
this.documentsService.downloadFiles(fileName).subscribe(file => {
let newBlob;
if(file.filename.match('.pdf')) {
newBlob = new Blob([file ], { type: "application/pdf" });
} else {
newBlob = new Blob([file ], { type: "image/jpg" });
}
const data = window.URL.createObjectURL(newBlob);
window.open(data, '_blank');
});
I tried opening a PDF file using the window.open(), but the window opens and closes automatically and the file is downloaded like any other file. How to make the pdf file open in new tab? There are no ad blockers installed.
From #barbsan idea, I changed the http headers and received a blob and used that to display the blob as pdf using window.open(). It worked.
Here is my sample code.
In service file
downloadPDF(url): any {
const options = { responseType: ResponseContentType.Blob };
return this.http.get(url, options).map(
(res) => {
return new Blob([res.blob()], { type: 'application/pdf' });
});
}
In component file
this.dataService.downloadPDF(url).subscribe(res => {
const fileURL = URL.createObjectURL(res);
window.open(fileURL, '_blank');
});
One liner solution to open a pdf file in new tab. You just need to have file url and use this function on button click.
window.open(url, '_blank');
you can display pdf fle in new tab by the line:
window.open(fileUrl, '_blank');
The fileUrl is a variable that contains the file path.
For the Angular 13 version
downloadPDF(url: string): Observable<Blob> {
const options = { responseType: 'blob' as 'json' };
return this.httpClient
.get<Blob>(url, options)
.pipe(map(res => new Blob([res], { type: 'application/pdf' })));
}
you need user the "target="_blank" in the tag ;
exemple: <a target="_blank" href="https://www.google.com/"> </a>
How to make it work in Angular 10, changes just a little bit, this in the service file from #K Harish answer
import { map } from 'rxjs/operators';
return this.http.get(url, options).pipe(map(
(res) => {
return new Blob([res], { type: 'application/pdf' });
}));
I am trying to use the cordova social sharing plugin for sharing video on social sites. So far what I have achieved is, I have successfully captured video using following code -
var options = {
limit: 1,
duration: 15
};
$cordovaCapture.captureVideo(options).then(function (videoData) {
$scope.videoUrl = videoData[0].fullPath;
}, function (err) {
// An error occurred. Show a message to the user
//alert("video error : "+err);
});
I can successfully find the captured video files url but unfortunately I can not share them to the social media sites. I have tried both of the following methods -
$cordovaSocialSharing
.share(message, subject, file, link)
and
$cordovaSocialSharing
.shareViaTwitter(message, image, link)
Now my question is -
Is there any way to share video through this approach?
If not, please let me know if there is any possible way for this.
N.B. : I have already bothered the Google a lot.
Thanks in advance.
my problem was passing a bad filePath, so i found a solution like below :
import {CaptureError, MediaFile, MediaCapture, CaptureImageOptions, Transfer} from "ionic-native";`
declare let cordova: any;
private static options = {
message: '', // not supported on some apps (Facebook, Instagram)
subject: '', // for email
files: [''], // an array of filenames either locally or remotely
url: ''
};
videoOptions: CaptureImageOptions = {limit: 1};
videoData: any;
captureVideo() {
MediaCapture.captureVideo(this.videoOptions)
.then(
(data: MediaFile[]) => {
this.videoData = data[0];
const fileTransfer = new Transfer();
fileTransfer.download(this.videoData.fullPath, cordova.file.applicationStorageDirectory + 'fileDir/filename.mp4').then((entry) => {
this.options.message = " Your message";
this.options.subject = "Your Subject";
this.options.files = [entry.toURL()];
this.options.url = "https://www.google.com.tr/";
SocialSharing.shareWithOptions(this.options);
}, (error) => {
});
},
(err: CaptureError) => {
}
);
}
As you see above, i just copy my video file to applicationStorageDirectory