Проблемы с обработкой шаблона.docx от рельсов до угловых

  1. Я новичок в Angular 4, мне нужно отправить файл шаблона.docx из Angular(внешний интерфейс) в rails(бэкэнд), а затем, когда пользователю требуется загрузить шаблон.docx и обработку с использованием docxtemplater

    Вот мой код для отправки файла с Angular на сервер rails:

    **component.ts**
    
    upload(event: any) 
      {
        const file = this.fileInput.nativeElement.files[0];
    
        this.reportService.uploadfile(file, this.report.id, this.user.clinic.id).subscribe( res => {
          },error => {
            this.flashMessagesService.show('Error uploading the template. ', { classes: ['alert', 'alert-danger'], timeout: 5000 })
          })
        this.download_report(this.user.clinic.id, this.report.id);
      }
    **service.ts**
      public uploadfile(file : File,report_id: number, clinic_id: number): Observable<Response> 
      {
        const formData = new FormData();
        formData.append("report_id", report_id.toString());
        formData.append("clinic_id", clinic_id.toString());
        formData.append("report", file);
        let headers = this._tokenService.currentAuthHeaders;
        headers.delete('Content-Type');
        let options = new RequestOptions({ headers: headers });
        return this._tokenService.request({
          method: 'post',
          url: environment.api_base + `/reports/uploadfile`,
          body: formData,
          headers: options.headers
        })
      }
    

    Вот мой код для получения файла с Angular на сервер rails:

      # POST /reports/uploadfile/
      def uploadfile
        url = "#{Rails.root}/reports/" + params[:clinic_id] + "/template/" + params[:report_id]
        dir = File.dirname("#{Rails.root}/reports/" + params[:clinic_id] + "/template/" + params[:report_id])
        FileUtils.mkdir_p(dir) unless File.directory?(dir)
        File.open(url, 'w+') do |f|
          f.write(params[:report].read.force_encoding('utf-8'))
        end
      end
    

    Вот мой код для получения файла с рельсов в Angular:

        **component.ts**
    download_report(clinic_id: number ,report_id: number) 
      {
        this.reportService.downloadfile(clinic_id, report_id).subscribe( res => {
         var JSZip = require('jszip'); 
         var Docxtemplater = require('docxtemplater');
          var zip = new JSZip();
          zip.file('file.docx',res['_body'],{binary: true});
          var doc = new Docxtemplater();
          doc.loadZip(zip);
    
          },error => {
            this.flashMessagesService.show('Error downloading the report. ', { classes: ['alert', 'alert-danger'], timeout: 5000 })
          })
      }
    
    
        **service.ts**
         public downloadfile(clinic_id: number,report_id: number ): any 
      {
        let params = {clinic_id: clinic_id, report_id: report_id}
        return this._tokenService.get('reports/downloadfile', {params: params});
    
       }
    

    Вот мой код для отправки файла с рельсов в Angular:

      # GET /reports/downloadfile/
      def downloadfile
        @url = "#{Rails.root}/reports/" + params[:clinic_id] + "/template/" + params[:report_id]
        send_file(@url,:filename => "report.doc", :type => 'application/msword')
      end
    

    Файл был отправлен нормально, после сохранения на сервере rails на диске, файл был открыт с помощью редактора, и все выглядит нормально, затем, когда файл был загружен и был сохранен на диске с помощью saveAs(), открывается DOCX штраф означает, что файл получен в порядке. Но если перед сохранением файла я пытаюсь обработать его с помощью docxtemplater, то выдает следующую ошибку внутри функции doc.loadZip(zip);

     core.es5.js:1084 ERROR XTInternalError {name: "InternalError", properties: {…}, message: "The filetype for this file could not be
    

    определено, поврежден ли этот файл?", стек: " Ошибка: тип файла для этого файла не может быть идеальным... ( http://localhost:4200/vendor.bundle.js:61365:26) "}

    Ответ сервера rails:

    _body
    :
    "��ࡱ�;��  F���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� ↵����
     !"#$%&'()*+,-./0123456789:;<=>?@ABCDE����G������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Root
    

    запись ↵! "# $% & '() +, -. / 012345 789:; = Word Microsoft Word-документ ↵MSWordDocWord.Document.8 9 q%↵[d dNormal $ a $ 1 $ $ A $ 3B OJQJCJmH sH KHPJnHtH ^ JaJ_H9.. WW8Num1z0OJQJ^J" " WW8Num2z0"WW" WW8Num2z1"!" WW8Num2z2" 1" WW8Num2z3" "A" WW8Num2z4" Q" WW8Num2z5" a" WW8Num2z6" q" WW8Num2z7" " WW8Num2z8B BAbsatz-StandardschriftartH HWW-Absatz-StandardschriftartJ JWW-Absatz-Standardschriftart1L LWW-Absatz-Standardschriftart11..BulletsOJQJPJ^JF FHeading $x$OJ QJ CJPJ^JaJ.B. Текст Body↵ x / List ^J↵@"@Caption! x x$CJ6^J↵aJ]& "&Index"$^J↵4 24Содержание таблицы #$> 1B> Заголовок таблицы $$a$$5\ l,b $2 F'3TQ g2@ 2 (↵ ↵ ↵ N A? C" <↵ C & TPG Times New Roman5 Symbol3 & rialAriali Лаборация SerifTimes New Romani Либерация SerifTimes New Roman? DejaVu Sans? Лохит Хинди5 Символ_ Открытыйсимвол Arial Unicode MSS & ibLiberation SansArial? H Лохит Хинди B hHrGrbg '… ¯ ~ A ~ o | ~ >I> ޟ ~~ ͗ _ 7{Ư3 |! Z7 {~ I Qc? ÿWao ~ Ww [oǿ ֿ 733ON? �XC�]?����Ư�$������l�������i���O����/>�����.��k>�����/Ľ���7�/>�^��˟�����~Z��|�}������͟��-�z_F^Zt�0d8hk�]%WK&����Քa/�~��K��E߷7TX2 �ߴ袥�Χ����)�Ԣ��P�a��hqH�ҢN��b���E��j���d�ZtȰ�Pa�:ԥE��↵�ߒyh����a����MZ�>*ÐajѦE�}S[��Ya�o?F/Z��0WC���C�Y|�n2L-ڴ�3��f�g�ᠭu��ߴ�;3�jh�e Ðaj�b���Ӿ--�|N��dZ�i�-��t�v؇j�H�T2ɥԷ�HӢM�>��-���ߔaj�灐�����C�%���M�>kk��d�aȰ7�9Z��0WC�!�>�:e��>�+��ah�EK7�d�:lSZ��0WC��E�c�0�m�����20�)�Pm����X�%���M�Ǧ�oZ���o�0���@�����@��Ih��E�s5d�Z���V}��6�$�WR2I-����-�~Ӣ-l�&WC�/�S�ÕT��mi��sB�%���M�6-����iQ'�\ �mZt�ܸ߾���,znS2Y�a�)�Ԣ�{K�6-�M�~ӢEZt��ߔah��E��0$9Z�i�"�d�:lSZ�i��� ����o�3a�Q�K}����-Ӂ���R_�~ }} УЭК Е: нВт森4k8Lix :�:� ��<���|��I��_����������b�����(Vyi���s���p3/��a�}��_��,�І�@�R_��I��s��U�E��U�EXա���<�tܮLO.�ɴ�ܛ����|��<L�i�*�"�a�jK�R_���tr:���~i5u�C�EX�iH�l�2X��<�u��c}>,�}��|��Ӻ7磞�a�O�(Vy� ��a���2$�]!�>ٯ��~��!�:�U�E��U�EXա���<��j��w|B�����0�gL� ����G��U��T�~��d��틽ai��yԫ|(����޽��Q��a�;y�_��ě,�~��jW��t״ι��>9S�j�ko���� �5�1�}R��+����1ӫ0���y�'���'��U>�w~�x��C��{_<jhý���wm'�*����t��:T{o���@NN��a�L�a˽�ʽ��r���6�L�}�ts��U��6�}��Խ}>$�~H�pul8��/ c�N��}>���Uݫ|50X�ߛ�{7���@�ìo��jWy:���_�����t~:|o��7O���� ����7�[Vu�>�ծ��'{g�V'�� �Wý��{��+Ǿ����^���.�A�Y��M�xSIaZ�a���>9S�jO�T�E���� ��A[��j��O2Y�Rm�ʳH�����gmam:3��~W^�I�ì�dPyiߖJ�HC{�v҃��|�y�2����ːT�]yyxc��χ�j�y�$�Է�TSI�d=�<�t3OC{ 'W��K7�>}>�<m/�R%Y�>T�EʥTI� ����I����J�.���U�ηg�mi�Ő��~���bH�vo*ɢ�jjQ'�~i���,���0�\ �і]��|�K��,R�*�"�R�$�t���Ő��6޴�2�'e�]�頍zX-��0V�>/�d��v�j*�"���g�n�o�V��gV77;~����U�!�v���X�d�.K��d�Z4KC�jƢ.-����a��ݳ�U_;�ս����}6}íޅC�듪��R�gC��6�Yա���!�v���i7�������{�t�WL�L�/��y�'���'{C��R���y��n>Đ��N����x�ͼ<�����������0��{C^�*O���r�x�V���Z?������al���!a��f��x��>Y�iu�*O}��>I_�Ӑ|�!�]��0,�o��U^j: z 3u:N Vy Vo +g î4 ծ t܆}RjiuH O 6N p y < O X ﵵ J KaW ' > L 9gHV | W 3G < o m Xl_g y 'g P {ːW ~ j | oX ۏ # n χd t > z i 1 y, ~ @:: i: у + jStc}^ и, ІaW} WSK}^> ֽ vı ] @ }> ua, | zu /} 4 U a8h ': >OCҷ: >OCXu_ Rc{50Ûu} mZgVy "WnEihjxqI}އ: у 0 [UL ܻ ZZ9ϫðj {ɽ (.7UQ>, I; vZG i w }^W B +f 6m y V E] u Y } C E f v Ԣφ lKK;ma[ S 9 D0dX ̢L ^K V3 = hӢ- " & 9 Z ه9Y " L* 6exR h f;hk 33 3 ^In0MmZY[X6| л ش~ӢMfGeRy) TIU3uWaoM-MZL }hn2WS> SER а:? Ða0TKWctז VBK> Dڰ дС))R > U}s u 6!Cҷ L,9Z \ fRy&! A- 3 ↵ H Ty o?Fwmi Ő6a ޶ iѦOE] N[=DjjjSʫgm,RnScZԅ mZ¾v4-LôZMKC_H-ڴ F * < X�6�hӢ�'�}�Iȶ7�5Vy&!����~)��3 پ�7��x���~˷;���ާ�.��t=�{ ���~�yν���wz齍����F3|���Oy�7�O�]���z��6z/��?�{k�Mo��{? /?�[����)-�����>�wy˧�+�T�--����ݻ�oz�����Ix!�1�jW�\�Wp�^ ��{%W�� ?��^��W�x.n����W�V�����^ ����Y�w�u�Y����h�gm��!�Ԣ��P�a��hqH�����n*�" m��?d]a�o?F/Zt�0�M} ��R�)����y���>���>����0ͧ�j �q�Ӫ��p&�V5�K��0\�W{o^ؘ�>)�ޕa���������>�/p5�N^��� �2$�n��d��'��(�g��݇�ECr܆��A>�<���>�/p5�����e�*�{ c.2Uy 癬 xoBYug ~ �wj�ڷG�:d�I°��o���~�Lޛ�aޞ�g�qM��:Ða�:Ðaii�-ܳqhC΄�3�↵�(�$��R�Քm�:�^���3��3�↵��MC���ȅ���I��Y.���|�����\>#��p��o��ʽ�+�J��+�r��ʽ�+�J��+�r��ʽ�+�J��+�r��ʽ�+�J��+�r��ʽ�+�J��+�r��ʽ�+�J��+�r��ʽ�+�J��+�r��ʽ�+�J��+�r��ʽ�+�J��+�r��ʽ�+�J��+�r��ʽ�+�J��+�����?��6.,��IEND�B "Корневая запись" F CompObj jOle↵ 1Table SummaryInformation(6DWordDocument uObjectPoolDocumentSummaryInformation8

1 ответ

Вот мой код для отправки файла с Angular на сервер rails:

    **component.ts**

    upload(event: any) 
      {
        const file = this.fileInput.nativeElement.files[0];

        this.reportService.uploadfile(file, this.report.id, this.user.clinic.id).subscribe( res => {
          },error => {
            this.flashMessagesService.show('Error uploading the template. ', { classes: ['alert', 'alert-danger'], timeout: 5000 })
          })
        this.download_report(this.user.clinic.id, this.report.id);
      }
    **service.ts**
      public uploadfile(file : File,report_id: number, clinic_id: number): Observable<Response> 
      {
        const formData = new FormData();
        formData.append("report_id", report_id.toString());
        formData.append("clinic_id", clinic_id.toString());
        formData.append("report", file);
        let headers = this._tokenService.currentAuthHeaders;
        headers.delete('Content-Type');
        let options = new RequestOptions({ headers: headers });
        return this._tokenService.request({
          method: 'post',
          url: environment.api_base + `/reports/uploadfile`,
          body: formData,
          headers: options.headers
        })
      }

Вот мой код для получения файла с Angular на сервер rails:

      # POST /reports/uploadfile/
      def uploadfile
        url = "#{Rails.root}/reports/" + params[:clinic_id] + "/template/" + params[:report_id]
        dir = File.dirname("#{Rails.root}/reports/" + params[:clinic_id] + "/template/" + params[:report_id])
        FileUtils.mkdir_p(dir) unless File.directory?(dir)
        File.open(url, 'w+') do |f|
          f.write(params[:report].read.force_encoding('utf-8'))
        end
      end

Вот мой код для получения файла с рельсов в Angular:

        **component.ts**
    download_report(clinic_id: number ,report_id: number) 
      {
        this.reportService.downloadfile(clinic_id, report_id).subscribe( res => {
 var JSZip = require('jszip'); 
 var Docxtemplater = require('docxtemplater');
 var file = new File([res],'report.doc',{type:'application/msword'});
 let reader = new FileReader();
 reader.readAsArrayBuffer(file);
 reader.onload = () => {
  this.doc = {
    filename: file.name,
    filetype: file.type,
    //To encode base64 (.docx does not work)
     value: reader.result
  };

  var zip = new JSZip(this.doc.value);
  var doc = new Docxtemplater();
  doc.loadZip(zip);
  doc.setData({
    nombre: 'John'
    });
  try 
  {
    doc.render()
  }
  catch (error) 
  {
    var e = { message: error.message, name: error.name, stack: error.stack, properties: error.properties}
    throw error;
  }

  var buf = doc.getZip().generate({type: 'nodebuffer'});
  var out = doc.getZip().generate({ type:"blob", mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}); //Output the document using Data-URI
  saveAs(out,"output.docx");
 }

},error => {
    this.flashMessagesService.show('Error downloading the report. ', { classes: ['alert', 'alert-danger'], timeout: 5000 })
})
      }


        **service.ts**
         public downloadfile(clinic_id: number,report_id: number ): any 
      {
           let params = {clinic_id: clinic_id, report_id: report_id}
return this._tokenService.get('reports/downloadfile', {params: params, responseType: ResponseContentType.Blob}).map(
  (res) => { return new Blob([res.blob()], { type: 'application/msword' })})

       }

Вот мой код для отправки файла с рельсов в Angular:

      # GET /reports/downloadfile/
      def downloadfile
        @url = "#{Rails.root}/reports/" + params[:clinic_id] + "/template/" + params[:report_id]
        send_file(@url,:filename => "report.doc", :type => 'application/msword')
      end
Другие вопросы по тегам