How to download an application from gmail api using javascript?

I am creating a web application to read my email messages using the gmail api. All methods work (users.messages.list, users.messages.get, etc.) and are displayed in console.log and on my HTML page. One thing, I noticed that I have to use atob to decode body.data strong> and paste into my HTML. Now I need to download or read the attachment for the file.docx example, and I use this example here after the callback, I noticed that I also need to decode, but if I do this, there is no link to download or read, only some code from the word microsoft If I copy this code and create a document and paste it, it says the file is damaged.

My code is:

function getAttachments(messageID, parts, callback) { //console.log(parts); var attachId = parts.body.attachmentId; var request = gapi.client.gmail.users.messages.attachments.get({ 'id': attachId, 'messageId': messageID, 'userId': 'me' }); request.execute(function (attachment) { callback(parts.filename, parts.mimeType, attachment); }); } if (att.length > 0) { for (var i in att) { getAttachments(response.id, att[i], function (filename, mimeType, attachment) { console.clear(); console.log(filename, mimeType, attachment); console.log(atob(attachment.data.replace(/-/g, '+').replace(/_/g, '/'))); inline.append('<a href="" style="display: block">' + filename + '</a>'); }); } } 

UPDATE

I found a solution here

+5
source share
1 answer

Try this solution.

HTML

 <a id="download-attach" download="filename"/> 

Js

 function getAttachments(messageID, parts, callback) { var attachId = parts.body.attachmentId; var request = gapi.client.gmail.users.messages.attachments.get({ 'id': attachId, 'messageId': messageID, 'userId': 'me' }); request.execute(function (attachment) { callback(parts.filename, parts.mimeType, attachment); }); } if (att.length > 0) { for (var i in att) { getAttachments(response.id, att[i], function (filename, mimeType, attachment) { let dataBase64Rep = attachment.data.replace(/-/g, '+').replace(/_/g, '/') let urlBlob = b64toBlob(dataBase64Rep, mimeType, attachment.size) let dlnk = document.getElementById('download-attach') dlnk.href = urlBlob dlnk.download = filename dlnk.click() URL.revokeObjectURL(urlBlob) } } function b64toBlob (b64Data, contentType, sliceSize) { contentType = contentType || '' sliceSize = sliceSize || 512 var byteCharacters = atob(b64Data) var byteArrays = [] for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize) var byteNumbers = new Array(slice.length) for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i) } var byteArray = new Uint8Array(byteNumbers) byteArrays.push(byteArray) } var blob = new Blob(byteArrays, {type: contentType}) let urlBlob = URL.createObjectURL(blob) return urlBlob } 
+1
source

Source: https://habr.com/ru/post/1236363/


All Articles