Angular: 400 не найден URL при попытке отобразить BLOB-объект docx - PullRequest
0 голосов
/ 02 апреля 2020

Я создал сервис SPRING BOOT, который может хранить файлы разных типов. Когда я пытался использовать этот сервис в ANGULAR, изображения также работают, а также в файлах pdf, но когда я пытаюсь отобразить файлы docx, возникает ошибка 400, а URL-адрес не найден.

Мой компонент .ts:

export class AppComponent {
  constructor(private httpClient: HttpClient) {}
  tag: string;
  selectedFile: File;
  retrievedFile: any;
  base64Data: any;
  retrieveResonse: any;
  message: string;
  UserTag: any;

  // Gets called when the user selects a file
  public onFileChanged(event) {
    //Select File
    this.selectedFile = event.target.files[0];
  }

  // Gets called when the user clicks on submit to upload the file
  onUpload() {
    console.log(this.selectedFile);

    // FormData API provides methods and properties to allow us easily prepare form data to be sent with POST HTTP requests.
    const uploadImageData = new FormData();
    uploadImageData.append("file", this.selectedFile, this.selectedFile.name);
    uploadImageData.append("tag", this.tag);

    // Make a call to the Spring Boot Application to save the file
    this.httpClient
          .post("http://localhost:8080/do", uploadImageData, {
            observe: "response"
          })
          .subscribe(response => {
            if (response.status === 200) {
              this.message = "Image uploaded successfully";
            } else {
              this.message = "Image not uploaded successfully";
            }
          });
      }

      // Gets called when the user clicks on retrieve filebutton to get the image from back end
      getFile() {
         // Make a call to Spring Boot to get the file Bytes.
        this.httpClient
          .get("http://localhost:8080/get/" + this.UserTag)
          .subscribe(res => {
            this.retrieveResonse = res;
            this.base64Data = this.retrieveResonse.fileContent;

        // treating the docx Files
        if (this.retrieveResonse.fileType == "docx") {
             var blob = new Blob([this._base64ToArrayBuffer(this.base64Data)], {
    type:
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  });

  const url = URL.createObjectURL(blob);
 // const url2 = this.sanitizer.bypassSecurityTrustResourceUrl(url);
  this.retrievedFile = window.open(
    "https://docs.google.com/viewer?url=" +
      url +
      "&pid=explorer&efh=false&a=v&chrome=false&embedded=true"
  );
}

_base64ToArrayBuffer.Ts

_base64ToArrayBuffer(base64) {
    const binary_string = window.atob(this.base64Data);
    const len = binary_string.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
      bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
  }

Метод get Spring Boot:

public DBFile getFile( String fileTag) throws IOException {

        final Optional<DBFile> retrievedFile = fileRepo.findByFileTag(fileTag);
        DBFile img = new DBFile(retrievedFile.get().getName(), retrievedFile.get().getFileType(),
                decompressBytes(retrievedFile.get().getFileContent()),retrievedFile.get().getAddedAt(),retrievedFile.get().getFileTag());

Метод распаковки:

/ / распаковать байты файла перед возвратом в приложение Angular

    public static byte[] decompressBytes(byte[] data) {
        Inflater inflater = new Inflater();
        inflater.setInput(data);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        byte[] buffer = new byte[1024];
        try {
            while (!inflater.finished()) {
                int count = inflater.inflate(buffer);
                outputStream.write(buffer, 0, count);
            }
            outputStream.close();
        } catch (IOException ioe) {
        } catch (DataFormatException e) {
        }
        return outputStream.toByteArray();
    }

    return img;
}

Любая помощь, ребята, пожалуйста?

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