发送字节数组给客户端

Send byte array to client

我可以将多部分表单数据发送到服务器。

客户端:

    const data = new FormData();
    data.append( 'name', uploadName );
    data.append( 'file', file ); //File is in the format UInt8Array

    Ajax( keycloak, {
            method: 'post',
            url: 'server/certificateDownload2',
            data: data
        },
        callbackFunction
    );

服务器端:

@POST
@Path( CERTIFICATE_DOWNLOAD2 )
@Consumes( MediaType.MULTIPART_FORM_DATA )
@Produces( MediaType.MULTIPART_FORM_DATA ) //Not sure about this type ?!?
public JrxmlDTO certificateDownload2( @MultipartForm JrxmlDTO dtoImportieren ) {
    return dtoImportieren; //For testing I am return immediately received DTO
}

这是我的回复DTO:

@Data
public class JrxmlDTO implements Serializable {

    private String name;

    private byte[] file;
}

但是我怎样才能在客户端正确接收到这个字节[]并再次将其保存为文件呢?

async function jrxmlDownloadCallback( response: AxiosResponse, certificateName: string ) {
  //response.data.response.file is a very long string
  //string is "3N4F928LCDJK...."
  const test = new Uint8Array( response.data.response.file );
  //After "new UInt8Array" my test-variable is an empty UInt8Array ??
  //How do I correctly convert the string to an correct UInt8Array?

  //The following gives me a string representing the uInt8Array
  // "120, 330, 13, 120, ..."
  //But how can I use this String as input for `new UInt8Array`?
  const uInt8ArrayAsString = atob( response.data.response.file );
  const UInt8Array = new Uint8Array ([uInt8ArrayAsString]); //Not working: new Uint8Array is awaiting a `ArrayBufferLike`

  const blob = new Blob( [test] );
  FileSaver.saveAs( await blob, 'test.jrxml' );
}

如何从服务器正确下载字节数组?

我是否必须在服务器上将 @Producer 属性 设置为 MediaType.MULTIPART_FORM_DATAApplication_JSON? 我是否必须解析客户端上的任何内容才能获得 blob?

解决办法。只是不知道有没有更好的方法。

在服务器上,将 MediaType 设置为应用程序 Json:

@POST
@Path( CERTIFICATE_DOWNLOAD2 )
@Consumes( MediaType.MULTIPART_FORM_DATA )
@Produces( MediaType.APPLICATION_JSON ) **//I changed to Application JSON**
public JrxmlDTO certificateDownload2( @MultipartForm JrxmlDTO dtoImportieren ) {
    return dtoImportieren; //For testing I am return immediately received DTO
}

在客户端我们首先要解码base-64编码的字符串。之后将字符串转换为数字:

async function jrxmlDownloadCallback( response: AxiosResponse, certificateName: string ) {
    const uInt8Array222 = atob( response.data.response.file ); //Decode base64 encoded string
    //Now we have UInt8Array as string: "60,93,50,..."
    //Parse this to numbers:
    const uintArray = new Uint8Array( uInt8Array222.split( ',' ).map( function ( eineZahl: any ) {
        return parseInt( eineZahl );
    } ) );
    const blob = new Blob( [uintArray] );
    FileSaver.saveAs( await blob, certificateName + '.jrxml' );
}