Как изменить имя файла в процессе загрузки в Jhipster (java + angular) - PullRequest
4 голосов
/ 25 января 2020

Это код, который, кажется, открывает его из контроллера:

 openFile(contentType, field) {
    return this.dataUtils.openFile(contentType, field);
  }

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

 <button type="submit" (click)="openFile(dataCleansing.fileContentType, dataCleansing.uploadedFileContent)"
                class=" btn
                btn-info viewTheme">
                <fa-icon [icon]="'download'"></fa-icon>
                </fa-icon>&nbsp;<span> Open/View File</span>
            </button>

Моя цель состоит в том, чтобы я загружал файл, и при его загрузке он содержит имя файла, а не download(1) или download(2), а в windows он использует некоторые случайные идентификаторы (не связанные с fileID). Мне бы хотелось, чтобы загруженный файл мог быть легко найден пользователем. Я попытался добавить заголовок content-filename. Но я не смог разобрать и установить. Похоже, встроенный сервис Jhipsters data-utils.service.ts контролирует функциональность загружаемого файла. который выглядит так внутри узловых модулей:

import { ElementRef } from '@angular/core';
/**
 * An utility service for data.
 */
export declare class JhiDataUtils {
    constructor();
    /**
     * Method to abbreviate the text given
     */
    abbreviate(text: string, append?: string): string;
    /**
     * Method to find the byte size of the string provides
     */
    byteSize(base64String: string): string;
    /**
     * Method to open file
     */
    openFile(contentType: string, data: string): void;
    /**
     * Method to convert the file to base64
     */
    toBase64(file: File, cb: Function): void;
    /**
     * Method to clear the input
     */
    clearInputImage(entity: any, elementRef: ElementRef, field: string, fieldContentType: string, idInput: string): void;
    /**
     * Sets the base 64 data & file type of the 1st file on the event (event.target.files[0]) in the passed entity object
     * and returns a promise.
     *
     * @param event the object containing the file (at event.target.files[0])
     * @param entity the object to set the file's 'base 64 data' and 'file type' on
     * @param field the field name to set the file's 'base 64 data' on
     * @param isImage boolean representing if the file represented by the event is an image
     * @returns a promise that resolves to the modified entity if operation is successful, otherwise rejects with an error message
     */
    setFileData(event: any, entity: any, field: string, isImage: boolean): Promise<any>;
    /**
     * Method to download file
     */
    downloadFile(contentType: string, data: string, fileName: string): void;
    private endsWith;
    private paddingSize;
    private size;
    private formatAsBytes;
}

Будем благодарны за любые указания и советы!

1 Ответ

4 голосов
/ 25 января 2020

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

downloadFile(contentType: string, data: string, fileName: string): void;

Попробуйте использовать этот метод вместо openFile(), что-то вроде этого в HTML:

<button type="submit" class="btn btn-info viewTheme" 
    (click)="downloadFile(dataCleansing.fileContentType, dataCleansing.uploadedFileContent)">
    <fa-icon [icon]="'download'"></fa-icon> Download File
</button>

Вы можете затем поместите в контроллер любое имя файла:

  downloadFile(contentType: string, field: string) {
    const filename = 'report_' + moment().format('YYYY-MM-DD-HH-mm');
    this.dataUtils.downloadFile(contentType, field, filename);
  }

В любом случае правильный заголовок для установки имени файла будет:

Content-Disposition: attachment; filename=custom_name.pdf;

Я не проверял это код.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...