Skip to content

Instantly share code, notes, and snippets.

@monolithed
Last active August 5, 2021 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monolithed/05c33c796ba2feb8b6dbd996c9d3dced to your computer and use it in GitHub Desktop.
Save monolithed/05c33c796ba2feb8b6dbd996c9d3dced to your computer and use it in GitHub Desktop.
Загрузка файла в Google Drive
  1. Откройте ваш файл и выберите "Инструменты"
  2. Выберите "Редактор скриптов"
  3. В появившемся окне вставьте первый скрипт (JS)
  4. Создайте на своем диске папку, куда будут складываться файлы
  5. Перейдите в новую папку
  6. Скопируйте в адресной строке ID папки (выглядит он примерно так 1jaST3NoIg63d0x0A1K7ppje8ZTjCWvIP)
  7. В функции saveFile замените значение ID на свой
  8. Нажмите иконку "Сохранить проект"
  9. Нажмите плюсик напротив "Файлы", чтобы добавить файл
  10. Выберите HTML
  11. В качестве название файла уаажите UploadFile
  12. Вставьте вторую часть кода (HTML)
  13. Нажмите иконку "Сохранить проект"
  14. Вернитесь обратно в свой файл и перезагрузите страницу
  15. Через пару секунд в верхнем меню появится пункт "Прикрепить файл"
  16. Выберите ячейку, куда будет вставляться файл
  17. Нажмите "Прикрепить файл" и загрузите файл в открытвшемся окне
function onOpen() {
    const ui = SpreadsheetApp.getUi();

    ui.createMenu('Прикрепить файл')
      .addItem('Прикрепить', 'openAttachmentDialog')
      .addToUi();
}

function openAttachmentDialog() {
    const html = HtmlService.createHtmlOutputFromFile('UploadFile');
    const ui = SpreadsheetApp.getUi();

    ui.showModalDialog(html, 'Прикрепить файл');
}

function saveFile({data, mimeType, fileName}) {
    const id = '1jaST3NoIg63d0x0A1K7ppje8ZTjCWvIP';

    const source = Utilities.base64Decode(data);
    const blob = Utilities.newBlob(source, mimeType, fileName);
    const folder = DriveApp.getFolderById(id);
    const file = folder.createFile(blob);
    const formula = `hyperlink("${file.getUrl()}";"${file.getName()}")`;

    const activeSheet = SpreadsheetApp.getActiveSheet();
    const selection = activeSheet.getSelection();
    const cell = selection.getCurrentCell();

    cell.setFormula(formula);

    return file.getId();
}
<!DOCTYPE html>
<html>
    <head>
        <base target="_top">
        <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
    </head>
        
    <script>
    function getFiles() {
        const uploadButton = document.getElementById('uploadButton');
    
        uploadButton.disabled = true;
    
        const progressText = document.getElementById('progress');
        const {files} = document.getElementById('files');
    
        let uploadCompletedCount = 0;
    
        const showProgress = (message) => {
            progressText.append(message || `Загрузка файла ${uploadCompletedCount + 1}/${files.length}`);
        };
    
        showProgress();
    
        Array.prototype.forEach.call(files, ({name: fileName}, index) => {
            const fr = new FileReader();
    
            fr.onload = ({target}) => {
                const [ext, data] = target.result.split(',');
                const mimeType = ext.match(/:(\w.+);/)[1];
    
                google.script.run.withSuccessHandler((id) => {
                    uploadCompletedCount++;
    
                    if (uploadCompletedCount >= files.length) {
                        showProgress('Загрузка завершена');
                        google.script.host.close();
                    }
                    else{
                        showProgress();
                    }
                })
                .saveFile({fileName, mimeType, data});
            };
    
            fr.readAsDataURL(files[index]);
        });
    }
    </script>
    
    <body>
        <!-- <input type="file" name="upload" id="files" multiple/> -->
        
        <input type="file" name="upload" id="files" />
        <input type='button' id="uploadButton" value='Загрузить' onclick='getFiles()' class="action" />
        
        <br />
        <br />
        
        <div id="progress"> </div> 
    </body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment