How to create file object from local file path [JavaScript] - javascript

I'm making cordova ios application with meteor. And I'm using one custom made camera plugin. After recording a video I get only local path of that video. I have to make File object with that path. I tried new File('etc/path') but it doesn't work.
Edit:
I tried to make blob and make New File([blob], 'name), but that doesn't work either.
Thanks,
Igor

Thanks #Bertrand, you gave me an Idea how to fix the problem. I wrote this:
window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs){
fs.root.getFile('output.mov', { create: true, exclusive: false }, function (fileEntry) {
fileEntry.file(function (file){
console.log(file)
});
}, (err) => {
console.log(err)
});
}, (err) => {
console.log(err)
});

Related

Adding file to dropzone Cypress

I am trying to add a pdf file to a dropzone in a Cypress test that Im creating
Ive added the cypress-upload-file package to help me do this.
In my commands.js file I have
Cypress.Commands.add("AddCandidate", function (candidate) {
cy.contains("Candidates").click()
cy.contains('Import Candidate').click()
cy.get('[id="resumeDz"]')
.attachFile({ './resumes': 'example.pdf', encoding: 'utf-8', subjectType: 'drag-n-drop' });})
and in my test I have
/// <reference types="cypress" />
describe('Add candidate', () => {
before(function () {
cy.visit(Cypress.env("home_page"));
cy.fixture('user').then(function (user) {
this.user = user
cy.SignIn({ email: (this.user.email), password: (this.user.password) })
})
})
it('Adds Candidate', function () {
cy.AddCandidate({})
})})
When running the test I get `"filePath" is not valid.
Please look into docs to find supported "filePath" values
Is there a specific way that i need to define the path ? Ive tried adding the full path, but Im still getting the same error. Is there something im missing ?`
SOLUTION
I ended up finding the solution.
Cypress.Commands.add("AddCandidate", function (candidate) {
cy.contains("Candidates").click()
cy.contains('Import Candidate').click()
cy.fixture('example.pdf', 'binary')
.then(Cypress.Blob.binaryStringToBlob)
.then(fileContent => {
cy.get('[type="file"]').attachFile({
fileContent,
filePath: 'example.pdf',
fileName: 'example.pdf',
});
cy.wait(1000)
cy.contains('Start').click()
cy.contains('Done').click()
});
})
The arguments to .attachFile() are a little messed up
cy.get('[id="resumeDz"]')
.attachFile('./resumes/example.pdf', {
encoding: 'utf-8',
subjectType: 'drag-n-drop'
});
presuming ./resumes/example.pdf is the path to the file relative to the fixtures folder.
With newer versions you can use the native cypress drag&drop action:
cy.get('#dropzone')
.selectFile('cypress/fixtures/file.txt', { action: 'drag-drop' });

Convert a PDF file to Google Doc using Google Drive API v3

I have uploaded a pdf file successfully to drive using a node server. However, I can not find a way to convert it to the google doc format so that it can be downloaded later as a docx document.
here is my actual code:
const fileMetadata = {
'name': 'new file.pdf',
//'mimeType': 'application/vnd.google-apps.document'
// trying to create it as a google doc directly does
// not work either
};
const media = {
mimeType: 'application/pdf',
body: fs.createReadStream(pdf)
};
drive.files.create({
resource: fileMetadata,
media,
fields: 'id'
}, (err, createdFile) => {
if (err) {
console.error(err);
} else {
// ------- COPY AS GOOGLE DOC
drive.files.copy({
fileId: createdFile.data.id,
requestBody:{
mimeType:'application/vnd.google-apps.document'
}
}, (err, googleDocFiles) => {
if (err) {
console.log(err)
// GaxiosError: Bad Request
// error: [
// { domain: 'global', reason: 'badRequest', message: 'Bad Request' } ]
} else {
console.log(googleDocFiles)
}
})
}});
What i have tried
using the files.upload method with the same requestBody returns a 200 response, however the pdf is unchanged
I know is possible, I did it before, using the copy method however now it not working and I have no clue why *sigh
EDIT
The mimeType in the request body is responsible for the 400 error, that is very weird since I am following the steps in the documentation here:
Import to Google Docs types section
this section is explicit about importing a CSV, however in the box under that section says that I can convert a pdf to doc using the corresponding mime type
I re-installed the package and it work

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.

uploadcare fileFrom ngCordova MediaFile

I am trying to upload a sound file from ngCordova's $cordovaCapture service to UploadCare. The uploadcare.fileFrom('object') keeps failing with an'upload' error. I have the public key set. I am able to upload the file by sending it through and tag and accessing document.getElementById('fileTag').files[0].
$cordovaCapture.captureAudio()
.then(function (audioData) {
return uploadcare.fileFrom('object', audioData[0])
.done(function (fileInfo) {
console.log(fileInfo);
}).fail(function (err) {
console.log(err);
})
})
the audioData[0] object looks like this
MediaFile {
end:0
fullPath:"file:/storage/emulated/0/Sounds/Voice%20002.m4a"
lastModified:null
lastModifiedDate:1481324751000
localURL:"cdvfile://localhost/sdcard/Sounds/Voice%20002.m4a"
name:"Voice 002.m4a"
size:49227
start:0
type:"audio/mpeg"
} __proto__:File
I thought the problem might be that the object is a MediaFile rather than a File but I could use some help casting one to the other.
FileEntry
filesystem:FileSystem
fullPath:"/Sounds/Voice 002.m4a"
isDirectory:false
isFile:true
name:"Voice 002.m4a"
nativeURL:"file:///storage/emulated/0/Sounds/Voice%20002.m4a"
__proto__:Entry
File
end:49227
lastModified:1481324751000
lastModifiedDate:1481324751000
localURL:"cdvfile://localhost/sdcard/Sounds/Voice%20002.m4a"
name:"Voice 002.m4a"
size:49227
start:0
type:"audio/mpeg"
__proto__:Object
using window.resolveLocalFileSystemUrl() you end up with the above FileEntry object that give the above File object but uploadcare still fails with an "upload" error.
Using ngCordova $cordovaFileTransfer() you can send audio files to uploadcare.
var fileName = filePath.split('/').pop();
var uploadcareOptions = {
fileKey: "file",
fileName: fileName,
chunkedMode: false,
mimeType: 'audio/mp4',
params: {
"UPLOADCARE_PUB_KEY": "upload-care-public-key",
"UPLOADCARE_STORE": 'auto',
fileName: fileName
}
};
return $cordovaFileTransfer.upload('https://upload.uploadcare.com/base/', filePath, uploadcareOptions)
The important part is to specify the mime type when sending files as uploadcare will assume it's a image otherwise.
uploadcare.fileFrom uploads a file from a native file object. Try this:
window.resolveLocalFileSystemURL(audioData[0].localURL,function(fileEntry){
fileEntry.file(function(file) {
uploadcare.fileFrom('object', file);
...
});
});

Chrome Apps : How to save blob content to fileSystem in the background?

In Chrome Apps, I'm downloading a blob content from a server using JavaScript XHR (Angular $http GET in particular, with response type 'blob')
How should I save this to chrome application's file system?
Currently using an Angular wrapper on HTML5 filesystem API
https://github.com/maciel310/angular-filesystem
I do not want to show user a popup (hence I can't use chrome.fileSystem. chooseEntry )
The chrome.fileSystem.requestFileSystem API is only supported by Kiosk-only apps.
Hence I'm using HTML5 FileSystem API instead of chrome's.
I'm using following code to make XHR to fetch blob.
$http({
url: SERVER_URL+"/someVideo.mp4",
method: "GET",
responseType: "blob"
}).then(function(response) {
console.log(response);
fileSystem.writeBlob(response.name, response).then(function() {
console.log("file saved");
}, function(err) {
console.log(err);
});
}, function (response) {
});
This is my writeBlob method
writeBlob: function(fileName, blob, append) {
append = (typeof append == 'undefined' ? false : append);
var def = $q.defer();
fsDefer.promise.then(function(fs) {
fs.root.getFile(fileName, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
if(append) {
fileWriter.seek(fileWriter.length);
}
var truncated = false;
fileWriter.onwriteend = function(e) {
//truncate all data after current position
if (!truncated) {
truncated = true;
this.truncate(this.position);
return;
}
safeResolve(def, "");
};
fileWriter.onerror = function(e) {
safeReject(def, {text: 'Write failed', obj: e});
};
fileWriter.write(blob);
}, function(e) {
safeReject(def, {text: "Error creating file", obj: e});
});
}, function(e) {
safeReject(def, {text: "Error getting file", obj: e});
});
}, function(err) {
def.reject(err);
});
return def.promise;
},
This shows SECURITY_ERR as It was determined that certain files are unsafe for access within a Web application, or that too many calls are being made on file resources.
What's the solution for this?
I've tried using --allow-file-access-from-files flag while launching app. It doesn't help.
Chrome Application's sandbox storage doesn't allow files to be stored in root directory (i.e. / )
Modify the code to save it in a specific sub-directory under it.
For example -
fileSystem.writeBlob("/new"+response.name, response).then(function() {
console.log("file saved");
}, function(err) {
console.log(err);
});
This would successfully save the file under /new/ directory.
To expand on this, here is a full example app on how to download a file and save the blob and display it back to the user.
https://github.com/PierBover/chrome-os-app-download-example

Categories

Resources