Welcome to the nuBuilder Forums!

Register and log in to access exclusive forums and content available only to registered users.

Uppy upload - change upload's filename?

Questions related to using nuBuilder Forte.
Post Reply
miasoft
Posts: 156
Joined: Wed Dec 23, 2020 12:28 pm
Location: Russia, Volgograd
Has thanked: 32 times
Been thanked: 7 times
Contact:

Uppy upload - change upload's filename?

Unread post by miasoft »

How to change the name of the Uppy-uploaded file (add a prefix, timestamp etc.)?
I read the documentation and tried to do according to these manual and examples - no result :oops:
Wbr, miasoft.
kev1n
nuBuilder Team
Posts: 4297
Joined: Sun Oct 14, 2018 6:43 pm
Has thanked: 71 times
Been thanked: 445 times
Contact:

Re: Uppy upload - change upload's filename?

Unread post by kev1n »

Can you post the procedure's PHP code? I'm using uppy in several places and have no issues with renaming.
miasoft
Posts: 156
Joined: Wed Dec 23, 2020 12:28 pm
Location: Russia, Volgograd
Has thanked: 32 times
Been thanked: 7 times
Contact:

Re: Uppy upload - change upload's filename?

Unread post by miasoft »

kev1n wrote: Fri Aug 26, 2022 1:05 pm Can you post the procedure's PHP code? I'm using uppy in several places and have no issues with renaming.
Code for input FileSystem ->HTMLtab

Code: Select all

<div id="#uppy_drag_drop_area#"></div>
<script src="https://releases.transloadit.com/uppy/locales/v3.0.0/ru_RU.min.js"></script>
<script>
    var $parentDiv = $('#' + '#parent_div#');
    var targetDiv = '#' + '#uppy_drag_drop_area#';

    var uppy = new Uppy.Core({
        autoProceed: false,
        allowMultipleUploadBatches: true,
        debug: false,
        restrictions: {
            maxFileSize: 5000000,
            minFileSize: null,
            maxTotalFileSize: null,
            maxNumberOfFiles: 1,
            minNumberOfFiles: null,
            allowedFileTypes: ['.jpg', '.jpeg', '.png', '.gif', '.pdf'],
            locale: 'Russian',
        },
        infoTimeout: 5000,
    })
    .use(Uppy.Dashboard, {
        inline: true,
        height: $parentDiv.cssNumber('height'),
        width: $parentDiv.cssNumber('width'),
        target: targetDiv,
        formData: true,
        showProgressDetails: true,
        replaceTargetContent: true,
        method: 'post'
    })

    .use(Uppy.XHRUpload, {
        endpoint: 'core/nuupload.php'

    })
    // .use(Uppy.setFileState(fileID, {
    //     xhrUpload: {
    //         fieldName: 'pic0'
    //     },
    // })

    uppy.setOptions({
        locale: {
            strings: {
                addMoreFiles: 'Добавить еще файлы',
                addingMoreFiles: 'Добавление дополнительных файлов',
                allowAccessDescription: 'Чтобы сделать фото или видео, пожалуйста, разрешите доступ к камере для этого сайта',
                allowAccessTitle: 'Пожалуйста, разрешите доступ к вашей камере',
                authenticateWithTitle: 'Пожалуйста, авторизуйтесь в %{pluginName}, чтобы выбрать файлы',
                authenticateWith: 'Подключиться к %{pluginName}',
                back: 'Назад',
                addMore: 'Добавить еще',
                browse: 'выберите',
                browseFiles: 'выберите',
                cancel: 'Отменить',
                cancelUpload: 'Отменить загрузку',
                chooseFiles: 'Выбрать файлы',
                closeModal: 'Закрыть окно',
                companionError: 'Не удалось подключиться к Companion',
                // «Готово» вместо «загрузка завершена», потому что кроме загрузки бывает encoding — транскодирование файлов
                complete: 'Готово',
                // «Нет подключения к интернету» — «Подключено к интернету»
                connectedToInternet: 'Подключено к интернету',
                copyLink: 'Скопировать ссылку',
                copyLinkToClipboardFallback: 'Скопируйте ссылку',
                copyLinkToClipboardSuccess: 'Ссылка скопирована в буфер обмена',
                creatingAssembly: 'Подготовка загрузки...',
                creatingAssemblyFailed: 'Transloadit: не удалось создать Assembly',
                dashboardTitle: 'Загрузчик файлов',
                dashboardWindowTitle: 'Окно загрузчика файлов (нажмите escape, чтобы закрыть)',
                dataUploadedOfTotal: '%{complete} из %{total}',
                done: 'Готово',
                dropHereOr: 'Перетащите файлы или %{browse}',
                dropHint: 'Перетащите файлы сюда',
                dropPasteBoth: 'Перетащите файлы, вставьте или %{browse}',
                dropPasteFiles: 'Перетащите файлы, вставьте или %{browse}',
                dropPasteFolders: 'Перетащите файлы, вставьте или %{browse}',
                dropPasteImportBoth: 'Перетащите файлы, вставьте, %{browse} или импортируйте из:',
                dropPasteImportFiles: 'Перетащите файлы, вставьте, %{browse} или импортируйте из:',
                dropPasteImportFolders: 'Перетащите файлы, вставьте, %{browse} или импортируйте из:',
                editFile: 'Редактировать файл',
                editing: 'Редактируется %{file}',
                emptyFolderAdded: 'Файлы не были добавлены — папка пуста',
                encoding: 'Обработка...',
                enterCorrectUrl: 'Неправильный адрес: пожалуйста, убедитесь что вы используете прямую ссылку на файл',
                enterUrlToImport: 'Введите адрес, чтобы импортировать файл',
                exceedsSize: 'Этот файл больше максимально разрешенного размера в %{size}',
                failedToFetch: 'Companion не смог загрузить файл по ссылке, пожалуйста, убедитесь, что адрес верный',
                failedToUpload: 'Ошибка загрузки %{file}',
                fileSource: 'Источник файла: %{name}',
                uploadComplete: 'Выгрузка завершена',
                filesUploadedOfTotal: {
                    '0': '%{complete} из %{smart_count} файла загружено',
                    '1': '%{complete} из %{smart_count} файлов загружено',
                    '2': '%{complete} из %{smart_count} файлов загружено',
                },
                filter: 'Фильтр',
            },
        },
    })
    uppy.on('complete', (result) => {

        if (result.successful.length >= 1) {
            const response = result.successful[0].response;
            if (response.status = 201) {

                if (window.nuOnFileUploaded) {
                    nuOnFileUploaded('FS', $parentDiv.attr('id'), response);
                }

            }
        }

    })
</script>
-->
You do not have the required permissions to view the files attached to this post.
Wbr, miasoft.
kev1n
nuBuilder Team
Posts: 4297
Joined: Sun Oct 14, 2018 6:43 pm
Has thanked: 71 times
Been thanked: 445 times
Contact:

Re: Uppy upload - change upload's filename?

Unread post by kev1n »

Did you create your own PHP Procedure?

To implement your own logic, clone that procedure, rename it and replace "NUUPLOADFILE_TEMPLATE" in the JS code with the Procedure nam
This is required if you want to rename the file.

Here's an example how I do it (slightly simplified):


HTML:

Code: Select all

<div id="#uppy_div#"></div>

<script>
    
    nuInitUppy();
    
    function nuInitUppy() {

        const $objId= $('#' + '#this_object_id#');
        const target = '#' + '#uppy_div#';
    
        let uppy = new Uppy.Core();
    
        uppy.use(Uppy.Dashboard, {
                inline: true
                , bundle: true
                , height: $objId.cssNumber('height')
                , width: $objId.cssNumber('width')
                , target: target
                , showProgressDetails: true
                , replaceTargetContent: true
                , method: 'post'
            })
            .use(Uppy.XHRUpload, {
                endpoint: 'core/nuapi.php'
            })
    
        uppy.on('file-added', (file) => {
            uppy.setMeta({ procedure: 'NUUPLOADFILE_picture', session_id: window.nuSESSION, record_id: nuRecordId(), employee_name: empfullname.value});
        })

        uppy.on('complete', (result) => {

            if (window.nuOnFileUploadComplete) {
                nuOnFileUploadComplete('FS', $objId.attr('id'), result);
            }
    
        })

    }

</script>

PHP Procedure with Code NUUPLOADFILE_picture

Code: Select all

require_once ('nusecurity.php');
// Allowed file extensions
$allowed = array('png', 'jpg', 'jpeg');

// Maximum file size
$maxfilesize = 5 * 1024 * 1024; // (5 MB)

$filename = nuSanitizeFilename(basename($_FILES['file']['name']));

$record_id = isset($_POST["record_id"]) ? $_POST["record_id"] : '';
$employee_name = isset($_POST["employee_name"]) ? $_POST["employee_name"] : '';
$target_dir = $_SERVER['DOCUMENT_ROOT']. "/resources/employees/pictures/"; 

$error = nuTranslate('Sorry, there was an error uploading your file.');

$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
    $data = ['error' => $error,
        'message' => 'Invalid File Type'];
    $result = json_encode($data);
}

$file = "Picture" ."_" . date('d.m.Y') ."_" . $employee_name ."_" . nuGenerateToken(20) . "_" . $record_id. "." . $ext;

$target_file = $target_dir . $file;

$filesize = $_FILES["file"]["size"];

if ($filesize > $maxfilesize) {
    $data = ['error' => $error,
        'message' => 'File size exceeded'];
    $result = json_encode($data);
}

try {
    if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) {
        $data = ['url' => $target_file,
            'file' => $file,
            'message' => 'The file ' . $file . ' has been uploaded.'];
        http_response_code(201);
        $result = json_encode($data);
    } else {
        throw new Exception('Unable to move the uploaded file to its final location:' . $target_file);
    }

} catch (\Throwable $th) {
    $data = ['message' => $error,
        'error' => $th->getMessage()];
    $result = json_encode($data);
}
miasoft
Posts: 156
Joined: Wed Dec 23, 2020 12:28 pm
Location: Russia, Volgograd
Has thanked: 32 times
Been thanked: 7 times
Contact:

Re: Uppy upload - change upload's filename?

Unread post by miasoft »

kev1n wrote: Fri Aug 26, 2022 1:40 pm Did you create your own PHP Procedure?
To implement your own logic, clone that procedure, rename it and replace "NUUPLOADFILE_TEMPLATE" in the JS code with the Procedure nam
This is required if you want to rename the file.
Thanks, kev1n!
I figured out how to rename the uploaded file. I changed only HTML-tab code:

Code: Select all

<div id="#uppy_drag_drop_area#"></div>
<script src="https://releases.transloadit.com/uppy/locales/v3.0.0/ru_RU.min.js"></script>
<script>
    var $parentDiv = $('#' + '#parent_div#');
    var targetDiv = '#' + '#uppy_drag_drop_area#';
    var v = nuGetProperty('record_id');    //added by miasoft
   // alert(v);
    var uppy = new Uppy.Core({
        autoProceed: false,
        allowMultipleUploadBatches: true,
        debug: false,
        restrictions: {
            maxFileSize: 5000000,
            minFileSize: null,
            maxTotalFileSize: null,
            maxNumberOfFiles: 1,
            minNumberOfFiles: null,
            allowedFileTypes: ['.jpg', '.jpeg', '.png', '.gif', '.pdf'],
            locale: 'Russian',

        },
        infoTimeout: 5000,
        onBeforeFileAdded: (currentFile, files) => {   //added by miasoft
            const name = v + '_' + currentFile.name;
            const modifiedFile = {
                ...currentFile,
                meta: {
                    ...currentFile.meta,
                    name
                },
                name
            };
           // alert(modifiedFile.name);
            return modifiedFile
            },
        })
        .use(Uppy.Dashboard, {
            inline: true,
            height: $parentDiv.cssNumber('height'),
            width: $parentDiv.cssNumber('width'),
            target: targetDiv,
            formData: true,
            showProgressDetails: true,
            replaceTargetContent: true,
            method: 'post'
        })

        .use(Uppy.XHRUpload, {
            endpoint: 'core/nuupload.php' 
        })
       ....
       ....
Wbr, miasoft.
Post Reply