Skip to content

Commit

Permalink
fix: Fixed file mime-type detection (fix #409)
Browse files Browse the repository at this point in the history
  • Loading branch information
edgardmessias committed Aug 19, 2021
1 parent 43ba3d4 commit 1609e34
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 3 deletions.
46 changes: 46 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@
"chalk": "^4.0.0",
"chrome-launcher": "^0.14.0",
"execa": "^5.0.0",
"file-type": "^16.5.3",
"fsevents": "^2.3.1",
"futoin-hkdf": "^1.3.2",
"latest-version": "^5.1.0",
Expand Down
14 changes: 11 additions & 3 deletions src/api/helpers/file-to-base64.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,27 @@
* along with WPPConnect. If not, see <https://www.gnu.org/licenses/>.
*/

const mimeTypes = require('mime-types');
import * as mimeTypes from 'mime-types';
import * as fileType from 'file-type';
import * as fs from 'fs';

/**
* Converts given file into base64 string
* @param path file path
* @param mime Optional, will retrieve file mime automatically if not defined (Example: 'image/png')
*/
export async function fileToBase64(path: string, mime?: string) {
export async function fileToBase64(path: string, mime?: string | false) {
if (fs.existsSync(path)) {
const base64 = fs.readFileSync(path, { encoding: 'base64' });
if (mime === undefined) {
mime = await mimeTypes.lookup(path);
mime = mimeTypes.lookup(path);
}
if (!mime) {
const result = await fileType.fromFile(path);
mime = result?.mime;
}
if (!mime) {
mime = 'application/octet-stream';
}
const data = `data:${mime};base64,${base64}`;
return data;
Expand Down

0 comments on commit 1609e34

Please sign in to comment.