Я пытаюсь адаптировать часть «Загрузить файл» в сценарий Google Apps. Мне удалось сделать первую часть (создание ожидающего файла) < /p>
Скрипт для адаптации (документация понятия): < /p>
// Open a read stream for the file
const fileStream = fs.createReadStream(filePath)
// Create form data with the (named) file contents under the `file` key.
const form = new FormData()
form.append('file', fileStream, {
filename: path.basename(filePath)
})
// HTTP POST to the Send File Upload API.
const response = await fetch(
`https://api.notion.com/v1/file_uploads/ ... adId}/send`,
{
method: 'POST',
body: form,
headers: {
'Authorization': `Bearer ${notionToken}`,
'Notion-Version': notionVersion,
}
}
)
// Rescue validation errors. Possible HTTP 400 cases include:
// - content length greater than the 20MB limit
// - FileUpload not in the `pending` status (e.g. `expired`)
// - invalid or unsupported file content type
if (!response.ok) {
const errorBody = await response.text()
console.log('Error response body:', errorBody)
throw new Error(`HTTP error with status: ${response.status}`)
}
const data = await response.json()
// ...
< /code>
Но я действительно борюсь с тем, как заменить структуру FormData ... < /p>
Изменить: вот более подробная информация и некоторые исправления (использование переменной формы) < /p>
Шаг 1 (создание файла): < /p>
(создание файла): < /p>
function createFileUpload(file) {
var service = getService(); // OAuth2 Notion service
if (service.hasAccess()) {
var url = 'https://api.notion.com/v1/file_uploads';
var filename = file.getName() ;
var contentType = file.getMimeType();
let options = {
method: 'POST',
muteHttpExceptions : true,
headers: {
accept: 'application/json',
'Notion-Version': API_VERSION,
Authorization: 'Bearer ' + service.getAccessToken(),
'content-type': 'application/json'
},
payload : JSON.stringify({
'filename': filename,
'content_type': contentType
})
};
var response = UrlFetchApp.fetch(url, options);
var json = JSON.parse(response.getContentText());
console.log("created: ");
Logger.log(JSON.stringify(json, null, 2));
return json;
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}
< /code>
Шаг 2 (загрузка файла): < /p>
function uploadFileContent(uploadUrl, file) {
var service = getService();
if (service.hasAccess()) {
const imgb64data = file.getBlob().getBytes();
var form = {
date : new Date(),
file : `data:image/png;base64,${imgb64data}`,
};
var options = {
method: 'POST',
muteHttpExceptions : false,
headers: {
'Notion-Version': API_VERSION,
Authorization: 'Bearer ' + service.getAccessToken(),
contentType: 'multipart/form-data'
},
body: form
};
Logger.log(JSON.stringify(options, null, 2));
var response = UrlFetchApp.fetch(uploadUrl, options);
if (!response.ok) {
const errorBody = response.text
console.log('Error response body:', errorBody)
throw new Error(`HTTP error with status: ${response.status}`)
}
return response.getResponseCode() === 200;
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}
< /code>
Часть загрузки возвращает ошибку: < /p>
Производительная проверка корпуса: body.file должен быть определен, вместо этого был
undefined
Наконец, вот основной код:
//File creation
var fileUpload = createFileUpload(gfile); // gfile: DriveApp file
var uploadUrl = fileUpload.upload_url;
var fileUploadId = fileUpload.id;
// File upload
var uploadSuccess = uploadFileContent(uploadUrl, gfile.getBlob());
if (!uploadSuccess) {
Logger.log('Failed to upload');
return;
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... -to-notion