我正在尝试编写一个代码,使用应用程序脚本将文件(图像)上传到Google云端硬盘。 请仔细阅读代码。 我无法从request.parameters中获取文件。我尝试使用formData,但它也没有用。
我收到以下错误:
从请求参数接收的文件对象的类型为字符串,但processData为false或
拒绝从'app script url'执行脚本,因为它的MIME类型('text / html')不可执行,并且启用了严格的MIME类型检查。
// Google App Script
function doPost(request) {
var result;
// get folder from the drive
try {
var dropbox = "tdsd";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var parmKeys = Object.keys(request.parameters);
Logger.log(parmKeys);
//get file
var blob = request.parameters.file;
var file = folder.createFile(blob);
result = {
status: 'success',
id: file.getId(),
url: file.getUrl(),
}
} catch (error) {
result = {status: 'error', error: error, boo: parmKeys, level: '8'};
}
return ContentService.createTextOutput(
request.parameters.prefix + '(' + JSON.stringify(result) + ')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
}
<form id="myForm">
<input type="text" placeholder="Your name.." id="myName">
<input type="file" name="myFile" id="myFile">
<input type="submit" value="Upload File" onclick="storeImage();">
</form>
<script>
function storeImage() {
event.preventDefault();
var myName = document.getElementById('myName').value;
var file = document.getElementById('myFile').files[0];
$.ajax({
url: 'Google_Script_Url?prefix=JsonpCallback',
method: 'POST',
type: 'POST',
dataType: 'jsonp',
data: {
file: file
},
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
mimeType: 'application/javascript',
success: function(results) {
console.log(JSON.stringify(results));
},
error: function(results) {
console.log(JSON.stringify(results));
}
});
}
</script>
答案 0 :(得分:1)
您的ajax请求存在多个问题
通过ajax上传文件的基本方法是使用FormData对象
var myName = document.getElementById('myName').value;
var file = document.getElementById('myFile').files[0];
var data = new FormData();
data.append(myName, file);
$.ajax({
url: 'Google_Script_Url',
type: 'POST',
data: data,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function(results) {
console.log(JSON.stringify(results));
},
error: function(results) {
console.log(JSON.stringify(results));
}
});