Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

This server class provides methods that allow operating the attachmentsДанный серверный класс содержит методы, позволяющие пользователям взаимодействовать с вложениями.

SimpleAttachment()


Instantiates a new empty SimpleAttachment objectИспользуйте этот конструктор класса для создания пустого объекта SimpleAttachment.

Code Block
languagejs
themeEclipse
titleSimpleAttachment
linenumberstrue
const attach = new SimpleAttachment();

base64Decode(data, strict)

This method returns an ASCII string decoded from the base64 string specified.

Parameter(s):


Используйте этот метод, чтобы вернуть строку ASCII, декодированную из указанной строки base64.

Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
NameTypeMandatoryDefault Value
dataString
YN

Return:

TypeDescriptionStringA decoded string.
ДаНет
strictBooleanНетtrue

Если входные данные содержат символы, не входящие в алфавит base64, а параметр strict задан как true, то метод base64_decode() вернёт false. Если параметр strict задан как false, символы, не входящие в алфавит base64, будут пропущены.

Возвращаемое значение:

ТипОписание
StringМетод возвращает декодированную строку.

ПримерExample:

Code Block
languagejs
themeEclipse
titlebase64Decode()
linenumberstrue
const attach = new SimpleAttachment();
const result =
  attach.base64Decode('TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ=');
ss.info(result);
// Информация: Lorem ipsum dolor sit amet

base64Encode(data)

This method returns a Base64 string from the string specified.

Parameter(s):


Используйте метод, чтобы преобразовать указанную строку в base64.

Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
NameTypeMandatoryDefault Value
dataString
Y
Да
N
Нет

ReturnВозвращаемое значение:

Type
Тип
Description
Описание
String
An encoded Base64 string
Метод возвращает закодированную строку base64.

ExampleПример:

Code Block
languagejs
themeEclipse
titlebase64Encode()
linenumberstrue
const attach = new SimpleAttachment();
const result =
  attach.base64Encode('Lorem ipsum dolor sit amet');
ss.info(result);
// Информация: TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ=

copy(sourceTableName, sourceID, targetTableName, targetID)

This method copies attachments from the source record to the target record.

Parameter(s):


Используйте этот метод, чтобы скопировать вложения из исходной записи в целевую. 

Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
NameTypeMandatoryDefault Value
sourceTableNameString
Y
Да
N
Нет
sourceIDString
Y
Да
N
Нет
targetTableNameString
Y
Да
N
Нет
targetIDString
Y
Да
N
Нет

ReturnВозвращаемое значение:

Type
Тип
Description
Описание
Boolean
This method returns 'true' if attachments have been copied successfully; otherwise, it returns 'false'.
Метод возвращает true,если вложения были успешно скопированы. В случае ошибки метод возвращает false.

ПримерExample:

Code Block
languagejs
themeEclipse
titlecopy()
linenumberstrue
const attach = new SimpleAttachment();
attach.copy('sys_email', '155964310500000059', 'task', current.sys_id);

deleteAttachment(

attachmentID

attachmentId)

This method deletes the specified attachment.

Parameter(s):

NameTypeMandatoryDefault ValueattachmentIDStringYN

Return:

TypeDescriptionVoidThis method does not return a value.

Используйте этот метод, чтобы удалить указанное вложение.

Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
attachmentIdStringДаНет

Возвращаемое значение:

ТипОписание
VoidМетод не возвращает значение.

ПримерExample:

Code Block
languagejs
themeEclipse
titledeleteAttachment()
const attach = new SimpleAttachment();
attach.deleteAttachment('157052637119478714');

getAttachmentUrlById(attachmentId)

This method allows getting the URL of the specified attachment at the cloud storage.

Parameter(s):

NameTypeMandatoryDefault ValueattachmentIdstringYN

Return:

TypeDescriptionStringThis method returns the attachment URL in the cloud storage.

Используйте этот метод, чтобы получить URL указанного вложения в облачном хранилище.

Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
attachmentIdStringДаНет

Возвращаемое значение:

ТипОписание
StringМетод возвращает URL-адрес вложения в облачном хранилище.

ПримерExample:

Code Block
languagejs
themeEclipse
titlegetAttachmentUrlById
linenumberstrue
const currentATTACH_ID = new SimpleRecord('sys_attachment');
current.get('163553718313772587');
const ATTACH_ID = current.sys_id;

const simpleAttach = new SimpleAttachment();
const attachUrl = simpleAttach.getAttachmentUrlById(ATTACH_ID);
ss.info(attachUrl);
//Info Информация: https://s3-{your-instance-url}/public-attachment/5/32/9bnc2pcb3axyfatgtc6lsi7...

getContent(

sysAttachment)

This method gets the attached content as a string.

Parameter(s):

NameTypeMandatoryDefault ValuesysAttachmentSimpleRecordYN

Return:

TypeDescriptionStringThe attachment content as a string.

attachmentId)


Используйте данный метод, чтобы получить содержимое в поле вложения Контент. Поле Контент автоматически заполняется текстовым содержимым прикрепленного файла .txt. 

Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
attachmentIdStringДаНет

Возвращаемое значение:

ТипОписание
String/ObjectМетод возвращает значение в поле вложения Контент. Если поле пустое или прикрепленный файл имеет другой формат, метод возвращает null.

ПримерExample:

Code Block
languagejs
themeEclipse
titlegetContent
linenumberstrue
const attach = new SimpleAttachment();
const content = ss.info(attach.getContent('157052637119478714168109939701169218'));
// Info: task active  additional_comments  approval_state ...

readBase64(attachmentId)

This method allows getting an encoded string from the specified attachment.


Используйте этот метод, чтобы получить закодированную строку из указанного вложения. Вместе с методом writeBase64() может использоваться для копирования вложений.

Note

Размер вложения не должен превышать 10 Мб. В случае превышения метод возвращает пустую строку, а в Журнале исключений (sys_log_exception)появляется запись

Note

The attachment size is limited up to 10 Mb; otherwise, the method throws an exception: File size exceeded allowed limit.

Parameter(s)Параметры:

NameНазваниеTypeТипMandatoryОбязательныйЗначение по умолчаниюDefault value
attachmentIdStringYДаNНет

ReturnВозвращаемое значение:

TypeТипDescriptionОписание
StringA base64-encoded string.Метод возвращает закодированную строку base64. В случае, если файл слишком большой, возвращаемая строка может быть пустой.

Пример:

Code Block
languagejs
themeEclipse
titlereadBase64()
linenumberstrue
const read = new SimpleAttachment();
ss.info(read.readBase64('159050716911764097168025458107121347'));
// Информация: 0YLQtdGB0YLQvtCy0YvQuSDQtNC+0LrRg9C80LXQvdGC

rename(attachmentId, fileName)

This method renames the specified attachment.

Parameter(s):


Используйте данный метод, чтобы изменить название файла и его расширение. 

Параметры:

НазваниеТипОбязательныйЗначение по умолчанию
NameTypeMandatoryDefault Value
attachmentIdString
Y
Да
N
Нет
fileNameString
Y
Да
N
Нет

ReturnВозвращаемое значение:

Type
Тип
Description
Описание
Void
This method does not return a value
Метод не возвращает значение.

ExampleПример:

Code Block
languagejs
themeEclipse
titlerename()
linenumberstrue
const DOC_ID = ss.getDocIdByIds(current.sys_db_table_id, current.sys_id);
const simpleAttach = new SimpleAttachment();
const attachRecord = new SimpleRecord('sys_attachment');
attachRecord.addQuery('record_document_id', DOC_ID);
attachRecord.addQuery('mime_content_type', 'application/json');
attachRecord.selectAttributes(['sys_id']);
attachRecord.query();
attachRecord.next();
simpleAttach.rename(attachRecord.sys_id, `${current.number} - ${current.subject}.json`);

write(documentId, fileName, content, contentType)

This method inserts an attachment to the record specified.

Parameter(s):


Используйте данный метод, чтобы создать и добавить вложение в указанную запись.

Параметры:

НазваниеТипОбязательныйЗначение по умолчаниюNameTypeMandatoryDefault Value
documentIdStringYДаNНет
filenameStringYДаNНет
contentStringYДаNНет
contentTypeStringYДаNНет

ReturnВозвращаемое значение:

Type
Тип
Description
Описание
String
The sys_ID of the attachment; in case of an error, it returns NULL.
Метод возвращает ID вложения; в случае ошибки возвращает null.

ПримерExample:

Code Block
languagejs
themeEclipse
titlewrite()
linenumberstrue
const simpleAttach = new SimpleAttachment();
const attachIDattachId =
    simpleAttach.write(
        ss.getDocIdByIds(current.sys_db_table_id, current.sys_id),
        'readme.json',
        JSON.stringify(current.getAttributes(), null, '\t'),
        'application/json'
    );

writeBase64(documentId, fileName, base64,

contentType)

mimeContentType)


Используйте данный метод для создания и добавления вложения к указанной записи, закодированного при помощи base64. Вы можете использовать этот метод вместе с readBase64() для копирования вложений.

Параметры:

НазваниеТипОбязательныйЗначение по умолчанию

This method inserts the attachment to the record specified using the Base64 encoding.

Parameter(s):

Default Value
NameTypeMandatory
documentIDStringYДаNНет
fileNameStringYДаNНет
base64StringYДаNНет
contentTypemimeContentTypeStringYДаNНет

ReturnВозвращаемое значение:

Type
Тип
Description
Описание
String
or NULLThe sys_ID of the attachment; in case of an error, it returns NULL.
Метода возвращает ID вложения;в случае ошибки возвращает null.

ПримерExample:

Code Block
languagejs
themeEclipse
titlewriteBase64()
linenumberstrue
const CURRENT_USER_DOC_ID = ss.getDocIdByIds(ss.getUser().sys_db_table_id, ss.getUserID());
const simpleAttach = new SimpleAttachment();
const base64Value = 'R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=';
const attachId = simpleAttach.writeBase64(
    CURRENT_USER_DOC_ID,
  	'file_example.gif',
    base64Value,
    'image/gif'
);
ss.info(attachId);
//Info Информация: 162245472311776172


Table of Contents
absoluteUrltrue
classfixedPosition