如何通过POST(doPost)将文件上传到Google脚本的Web App? [英] How to upload a file via POST (doPost) to a Google Script's Web App?

查看:89
本文介绍了如何通过POST(doPost)将文件上传到Google脚本的Web App?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与此相同:使用doPost将文件上传到Google Web Apps



如何从另一个域直接将文件上传到Google脚本的Web应用程序?我在这个问题上回答了一个解决方法,以base64字符串转换文件,但问题仍然存在。是否可以将文件上传到Google脚本或仅字符串?

解决方案

文件不能直接通过doPost()本地PC上HTML格式的GAS。因为multipart / form-data可能无法用于doPost()。因此,转换Base64导致解决方案,如你所说。



有2种方法可以通过doPost()上传文件。



1。从GAS项目的HTML表单上载文件



这会在GAS项目中使用GAS和HTML上传文件。在这种情况下,该文件不会由脚本转换为Base64。 (它可能会转换为内部过程。)

2。在本地PC上从HTML表单上载文件



在本地PC上从HTML表单上传文件。 GAS控制doPost()。在这种情况下,文件被编码为Base64并作为文本数据上传,然后使用GAS将其解码为文件。






1。从GAS项目的HTML表单上传文件






  1. 以下示例脚本和HTML必须制作成Google Apps脚本项目。

  2. 部署GAS项目作为web应用。 https://developers.google.com/apps-script/guides/web并检索URL。 在更新脚本后,必须将其更新为新版本。

Form.html

  < HTML> 
< body>
< form>
< input type =filename =upFile>
< input type =buttonvalue =okonclick =google.script.run.upload(this.parentNode)>
< / form>
< / body>
< / html>

脚本

 函数doGet(){
return HtmlService.createHtmlOutputFromFile('Form.html');
}

函数上传(e){
DriveApp.createFile(e.upFile);
}






2。从本地PC上的HTML表单上载文件



与上述规则几乎相同。脚本放在GAS项目上。但是,HTML表单被放置在本地PC上。



脚本

 函数doGet(e){
返回消息(Error:no parameters);


函数doPost(e){
if(!e.parameters.filename ||!e.parameters.file){
return message(Error :错误的参数);
} else {
var data = Utilities.base64Decode(e.parameters.file,Utilities.Charset.UTF_8);
var blob = Utilities.newBlob(data,MimeType.PNG,e.parameters.filename);
DriveApp.createFile(blob);
返回消息(已完成);



函数消息(msg){
返回ContentService.createTextOutput(JSON.stringify({result:msg}))。setMimeType(ContentService.MimeType上传.json);

HTML

 <!DOCTYPE html> 
< html>
< head>
< meta charset =UTF-8>
< script src =http://code.jquery.com/jquery-latest.jstype =text / javascript>< / script>
< / head>
< body>
< input type =fileid =file>

< script type =text / javascript>
$(function(){
var url ='https://script.google.com/macros/s/[Project ID] / exec';
var params = {
filename:'samplefile',
imageformat:'PNG'
};

$('#file')。on(change,function(){
var file = this.files [0];
var fr = new FileReader();
fr.onload = function(e){
params.file = e.target。 result.replace(/^.*,/,'');
postJump();
}
fr.readAsDataURL(file);
});

function postJump(){
var html ='< form method =postaction ='+ url +'id =postjumpstyle =display:none;>';
Object.keys(params).forEach(function(key){
html + ='< input type =hiddenname ='+ key +'value ='+ param s [key] +'>';
});
html + ='< / form>';
$(body)。append(html);
$('#postjump')。submit();
$('#postjump')。remove();
}
});
< / script>
< / body>
< / html>

此示例脚本假设上传PNG文件作为测试。如果你想上传其他文件,请更改MIME类型。 https://developers.google.com/apps-script/reference/ base / mime-type



对于HTML示例,选择文件时会上传文件。



如果这对你有帮助,我很高兴。

My question is exactly as this one: Upload a file to a Google Web Apps with doPost

How to upload a file directly to a Google Script's Web App from another domain? I answered a workaround in that question to convert the file in a base64 string but the question remains. Is it possible to upload a file to Google Scripts or only strings?

解决方案

Files cannot be uploaded directly by "doPost()" of GAS from HTML form on local PC. Because "multipart/form-data" may be not able to be used for "doPost()". So converting Base64 leads to the solution as you say.

There are 2 ways for uploading files by "doPost()".

1. Upload a file from HTML form on GAS project

This uploads a file using GAS and HTML in GAS project. In this case, the file doesn't convert to Base64 by the script. (It may convert as the internal process.)

2. Upload a file from HTML form on local PC

This uploads a file from HTML form on local PC. GAS controls "doPost()". In this case, the file is encoded to Base64 and upload as text data, and then decoded to the file using GAS.


1. Upload a file from HTML form on GAS project

Rule :

  1. Following sample script and HTML have to be made into a project of Google Apps Script.

  2. Deploy the GAS project as a web application. https://developers.google.com/apps-script/guides/web And retrieve URL.

  3. After updated the script, it has to be updated as a new version.

Form.html :

<html>
  <body>
    <form>
      <input type="file" name="upFile">
      <input type="button" value="ok" onclick="google.script.run.upload(this.parentNode)">
    </form>
  </body>
</html>

Script :

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

function upload(e) {
  DriveApp.createFile(e.upFile);
}


2. Upload a file from HTML form on local PC

The rule is almost the same to above one. The script is placed on GAS project. But HTML form is placed on local PC.

Script :

function doGet(e) {
  return message("Error: no parameters");
}

function doPost(e) {
  if (!e.parameters.filename || !e.parameters.file) {
    return message("Error: Bad parameters");
  } else {
    var data = Utilities.base64Decode(e.parameters.file, Utilities.Charset.UTF_8);
    var blob = Utilities.newBlob(data, MimeType.PNG, e.parameters.filename);
    DriveApp.createFile(blob);
    return message("completed");
  }
}

function message(msg) {
  return ContentService.createTextOutput(JSON.stringify({result: msg})).setMimeType(ContentService.MimeType.JSON);
}

HTML :

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
</head>
<body>
    <input type="file" id="file">

    <script type="text/javascript">
        $(function(){
            var url = 'https://script.google.com/macros/s/[Project ID]/exec';
            var params = {
                filename: 'samplefile',
                imageformat: 'PNG'
            };

            $('#file').on("change", function() {
                var file = this.files[0];
                var fr = new FileReader();
                fr.onload = function(e) {
                    params.file = e.target.result.replace(/^.*,/, '');
                    postJump();
                }
                fr.readAsDataURL(file);
            });

            function postJump(){
                var html = '<form method="post" action="'+url+'" id="postjump" style="display: none;">';
                Object.keys(params).forEach(function (key) {
                    html += '<input type="hidden" name="'+key+'" value="'+params[key]+'" >';
                });
                html += '</form>';
                $("body").append(html);
                $('#postjump').submit();
                $('#postjump').remove();
            }
        });
    </script>
</body>
</html>

This sample script supposes to upload a PNG file as a test. If you want to upload other files, please change mime type. https://developers.google.com/apps-script/reference/base/mime-type

For HTML sample, the file is uploaded when the file is selected.

If this will be helpful for you, I'm glad.

这篇关于如何通过POST(doPost)将文件上传到Google脚本的Web App?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆