Upload Files lên Google Drive qua Form HTML

Upload Files lên Google Drive qua Form HTML

 - Đăng nhập vào tài khoản Google của bạn và đi đến địa chỉ https://www.google.com/script/start/ và click vào nút Start Scripting
- Dán đoạn mã dưới đây vào file *.gs và lưu lại

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('form.html');
}

function uploadFiles(form) {

  try {

    var dropbox = "Student Files"; // tên thư mục trong Google Drive
    var folder, folders = DriveApp.getFoldersByName(dropbox);

    if (folders.hasNext()) {
      folder = folders.next();
    } else {
      folder = DriveApp.createFolder(dropbox);
    }

    var blob = form.myFile;   
    var file = folder.createFile(blob);   
    file.setDescription("Uploaded by " + form.myName);

    return "File uploaded successfully " + file.getUrl();

  } catch (error) {

    return error.toString();
  }


}


- Tiếp theo, tạo một file với tên form.html bằng cách vào menu File ~> New ~> Html file


<form id="myForm">

    <input type="text" name="myName" placeholder="Your name..">
    <input type="file" name="myFile">
    <input type="submit" value="Upload File"
           onclick="this.value='Uploading..';
                    google.script.run.withSuccessHandler(fileUploaded)
                    .uploadFiles(this.parentNode);
                    return false;">
</form>

<div id="output"></div>

<script>
    function fileUploaded(status) {
        document.getElementById('myForm').style.display = 'none';
        document.getElementById('output').innerHTML = status;
    }
</script>

<style>
 input { display:block; margin: 20px; }
</style>

















- Tại menu Run  ~> doGet để ủy quyền cho các kịch bản. Để nó có thể tải các tập tin từ form.html lên Google Drive của bạn
- Tiếp theo, chọn Publish ~> Deploy as web app và nhấn Save New Version, cấp quyền truy cập vào ứng dụng bằng cách chọn trình đơn thả xuống (bạn có thể chọn bất cứ ai cũng có thể tải file lên Google Drive của bạn bằng cách chọn Anyone, even anonymous). Và bạn sẽ được cung cấp một địa chỉ bất cứ ai cũng có thể truy cập vào địa chỉ này để tải các tập tin lên Google Drive của bạn.

0 nhận xét:

Đăng nhận xét

Tìm kiếm