Búsqueda de sitios web

typescript - Cómo cambiar el nombre del archivo durante el proceso de descarga en Jhipster (java + angular)


Este es el código que parece abrirlo desde el controlador:

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

y en el HTML esto se usa al pasar datos de un objeto devuelto por el servicio de la siguiente manera:

 <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>

Mi objetivo es que descargue el archivo y, cuando esté descargado, conserve el nombre del archivo y no aparezca como download(1) o download(2) y en Windows utilice algunos IDs aleatorios (no relacionados con el fileID). Me gustaría que el archivo descargado pudiera ser localizado fácilmente por el usuario. Intenté agregar el encabezado content-filename, pero no pude analizarlo ni configurarlo. Parece que el servicio incorporado de JHipster llamado data-utils.service.ts controla la funcionalidad de descarga de archivos, que se ve así dentro de los módulos de Node:

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;
}

¡Cualquier indicación y consejo sería muy apreciado!

Respuesta #1

Supongo que lo que realmente quieres es descargar archivos, no abrirlos. JhiDataUtils tiene un método específicamente para esto:

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

Intenta usar ese método en lugar de openFile(), algo así en el HTML:

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

Luego puedes poner el nombre de archivo que quieras en el controlador:

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

En cualquier caso, el encabezado correcto para establecer el nombre de un archivo adjunto sería:

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

No probé este código.

Artículos relacionados