PWA not sharing file with navigator.share, only dowload - javascript

This is my code
let f: any = XLSX.writeFile(wb, this.generarNombre(pedido.folio), {
bookType: 'xlsx',
type: 'array'
})
let data: Blob = new Blob([f], { type: EXCEL_TYPE })
let file = new File([data], this.generarNombre(pedido.folio), {
type: EXCEL_TYPE
})
let navigator = window.navigator as any
return new Promise((resolve, reject) => {
let data = {
files: [file],
title: this.generarNombre(pedido.folio),
text: pedido.folio
}
if (navigator.canShare(data))
navigator.share(data).then(result => resolve(result))
else reject('No soportado por el dispositivo')
})
}
My application is a PWA and it is installed successfully in android, the problem is that instead of sharing with the native option of android it only downloads the file. How can i solve this?

You can implement directly and check this out as in web.dev here
Or better use this pwa library, pwafire;
pwa.Share({
// Title of what to share
title: "Some title..",
// Text to share
text: "Some text...",
// List of files to share...
files: file_list
};)

Related

Cypress: How to test upload a folder with files and subfolders?

I'm having an issue to test uploading a folder with files and subfolders. If I add folder structure to the fixture then cy.fixture() command doesn't recognize that is a directory that I want to upload but it looks inside the directory to find the files. I have tries also to use the cy.readFile() but I couldn't make it to work.
I have tried to create drag and drop command like this:
Cypress.Commands.add('dragAndDropFolder', (fileUrl, type = '') => {
return cy.readFile(fileUrl, 'binary')
.then(Cypress.Blob.binaryStringToArrayBuffer)
.then(blob => {
const nameSegments = fileUrl.split('/');
const name = nameSegments[nameSegments.length - 1];
const testFile = new File([blob], name, { type });
const event = {
dataTransfer: {
isDirectory: true,
isFile: false,
fullPath: `#${fileUrl}`,
files: [testFile],
items: [{ kind: 'file', type }],
types: ['Files'],
},
};
return cy
.get('[data-test-dropzone="true"]')
.first()
.trigger('dragenter', event)
.trigger('drop', event);
});
});
Another thing I have tried to use a our different functionality which is simple upload button and the attachFile() plugin:
cy.readFile('client/testfolder', 'binary').then(file => {
cy.get('#multiple_file_uploads_input').attachFile(file)
});
Drag and drop functionality is written in Elixir and this is how data transfer looks like:
{
isDirectory: true,
isFile: false,
fullPath: '#{path}',
createReader() {
return {
sentEntries: false,
readEntries(callback) {
if (!this.sentEntries) {
this.sentEntries = true;
callback([#{Enum.join(entries, ",")}]);
} else {
callback([]);
}
},
};
},
}
At least on Elixir side the fullPath: '#{path}', will be substituted by the real path like fullPath: '/some/path', so you need to remove hash (#) from your path at JavaScript side here fullPath: '#${fileUrl}',, probably could be just fullPath: fileUrl,

React Open file dialog

I am trying to open a File Dialog Box with React, so that the user can select a folder and save the file in that particular folder, however I cannot manage to do that. My code looks like this at the moment:-
const exportToCSV = (csvData, fileName) => {
const ws = XLSX.utils.json_to_sheet(csvData);
const wb = { Sheets: { 'data': ws }, SheetNames: ['data'] };
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
const data = new Blob([excelBuffer], {type: fileType});
FileSaver.saveAs(data, fileName + fileExtension);
}
const openDialogWindow = () => {
// Open dialog here and get the folder name
exportToCSV(csvData, (folderName + fileName))
};
return (
<button
id="btnExportToCSV"
onClick={(e) => openDialogWindow()}
>
Export Tasks To Excel
</button>
)
so in my openDialogWindow, I would like to have the option to open the dialog box, and let the user select a folder that I can then attach to the pre-defined fileName. This will give the user the option to save the file in his chosen directory.
Is this possible?
Thanks for your help and time!

React | Facebook JS API : Error code 100 when trying to upload multiple images to my page feed

In a first function, I upload multiple images to page-id/photos and receive a positive response with all the ids of these images.
The next part however is where I'm stuck; I am now trying to create a post with multiple images to my Facebook page timeline. However, I'm getting a weird error response claiming that I already have uploaded my images.
I've even followed Facebook's own example from their documentation using Open Graph Explorer, but that just returns another error
Function to send image:
(works without a problem)
sendFacebookImagePost(page) {
const attached_media = []
for(let i = 0; i < this.state.upload_imgsrc.length; i++) {
let reader = new FileReader();
reader.onload = (e) => {
let arrayBuffer = e.target.result;
let blob = new Blob([arrayBuffer], { type: this.state.upload_imgsrc[i].type });
let data = new FormData()
data.append("source", blob)
data.append("message", this.state.fb_message)
data.append("no_story", true)
data.append("published", true)
axios({
method: "post",
url: "https://graph.facebook.com/" + page.id + "/photos?access_token=" + page.accessToken,
data: data
})
.then(response => {
attached_media.push({media_fbid: response.data.id})
if (attached_media.length === this.state.upload_imgsrc.length) {
this.sendFacebookPost(page, attached_media)
}
})
.catch(error => {
console.log(error);
})
}
reader.readAsArrayBuffer(this.state.upload_imgsrc[i]);
}
}
Function to send post:
(Here is where the error happens)
sendFacebookPost(page, attached_media) {
let data = {
message: this.state.fb_message,
link: this.state.fb_link,
attached_media: attached_media
// this is what attached_media returns:
// [
// {media_fbid: response.data.id},
// {media_fbid: response.data.id}
// ]
}
axios({
method: "post",
url: "https://graph.facebook.com/" + page.id + "/feed?access_token=" + page.accessToken,
data: data
})
.then( () => this.setState({fb_successMessage: "Post successful!", fb_errorMessage: ""}) )
.catch(error => {
console.log(error);
})
}
Error code
error: {
code: 100
error_subcode: 1366051
error_user_msg: "These photos were already posted."
error_user_title: "Already Posted"
fbtrace_id: "Cl9TUTntOZK"
is_transient: false
message: "Invalid parameter"
type: "OAuthException"
}
My try on Open Graph Explorer
Problem solved.
The part that went wrong is where I add the following to my image post:
data.append("published", true). Apparently, images you want to use in a multi photo post have to be set to published: false before they can be used in a post. Otherwise, Facebook sees this as already uploaded.

Ionic 3 - download a file to directory

I have the similar problem like here:
How to download file to Download's directory with Ionic Framework?
I got success alert after download but I can't see the file in an Android file explorer under the path displayed after succeed download: file:///data/user/0/io.ionic.fileTest/image.jpg
My code:
download(){
const fileTransfer: FileTransferObject = this.transfer.create();
const url = "http://cdna.allaboutvision.com/i/conditions-2016/heterochromia-kate-bosworth-660x660-with-credit.jpg";
fileTransfer.download(url, this.file.dataDirectory + 'laska.jpg', true).then((entry) => {
const alertSuccess = this.alertCtrl.create({
title: `Download Succeeded!`,
subTitle: `was successfully downloaded to: ${entry.toURL()}`,
buttons: ['Ok']
});
alertSuccess.present();
}, (error) => {
const alertFailure = this.alertCtrl.create({
title: `Download Failed!`,
subTitle: `was not successfully downloaded. Error code: ${error.code}`,
buttons: ['Ok']
});
alertFailure.present();
});
}
Could I somehow manage to save this file in e.g "Download" folder or "Documents"? I also tried changing destination path to:
cordova.file.externalRootDirectory + '/Download/'
In that case, I received error 1.
In many examples I see people use
window.requestFileSystem()
but it looks like the window doesn't have this method for me. I use visual studio code and ionic 3.
You got little bit mistake in fileTransfer.download
instead of this.file.applicationStorageDirectory use this.file.dataDirectory
Working code that downloads a file to Downloads directory:
downloadFile() {
this.fileTransfer.download("https://cdn.pixabay.com/photo/2017/01/06/23/21/soap-bubble-1959327_960_720.jpg", this.file.externalRootDirectory +
'/Download/' + "soap-bubble-1959327_960_720.jpg").then()
}
getPermission() {
this.androidPermissions.hasPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE)
.then(status => {
if (status.hasPermission) {
this.downloadFile();
}
else {
this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE)
.then(status => {
if(status.hasPermission) {
this.downloadFile();
}
});
}
});
}

Uploading file to PouchDB/CouchDB

I'm building a mobile app with Cordova. I am using PouchDB for local storage so the app works without internet. PouchDB syncs with a CouchDB server so you can access your data everywere.
Now, i've got to the point where I need to add a function to upload (multiple) files to a document. (files like .png .jpg .mp3 .mp4 all the possible file types).
My original code without the file upload:
locallp = new PouchDB('hbdblplocal-'+loggedHex);
function addItem() {
//get info
var itemTitle = document.getElementById('itemTitle').value;
var itemDesc = document.getElementById('itemDesc').value;
var itemDate = document.getElementById('itemDate').value;
var itemTime = document.getElementById('itemTime').value;
//get correct database
console.log(loggedHex);
console.log(loggedInUsername);
//add item to database
var additem = {
_id: new Date().toISOString(),
title: itemTitle,
description: itemDesc,
date: itemDate,
time: itemTime
};
locallp.put(additem).then(function (result){
console.log("Added to the database");
location.href = "listfunction.html";
}).catch(function (err){
console.log("someting bad happened!");
console.log(err);
});
}
I'll add a link to a JSfiddle where I show my attempt to add the file upload. i've also included the html part.
link to jsfiddle: click here
I've noticed an error in the console about there not being a content-type.
Is there someone who can help me?
I think you're not setting the content_type of your attachment right. Try changing type to content_type like so:
var additem = {
_id: new Date().toISOString(),
title: itemTitle,
description: itemDesc,
date: itemDate,
time: itemTime,
_attachments: {
"file": {
content_type: getFile.type,
data: getFile
}
}
};
Also see the docs for working with attachments.

Categories

Resources