【问题标题】:How to create a download button for multiple files using Liferay and JavaScript?如何使用 Liferay 和 JavaScript 为多个文件创建下载按钮?
【发布时间】:2017-10-20 05:59:26
【问题描述】:

单击时我试图制作一个按钮,它将文件下载为 zip 文件。我试图从给定的 url 将文件加载到 Zip 中。 我正在使用 Liferay 6.1。

JSP 文件中的脚本声明是否正确?

我已经在 liferay-portlet.xml 中指定了 jszip.js。

<footer-portlet-javascript>/js/jszip.js</footer-portlet-javascript>

我必须使用 Liferay AUI Taglib 标签还是一个简单的 javaScript 标签才能完成这项工作?

&lt;aui:script&gt;&lt;/aui:script&gt;&lt;script type="text/javascript"&gt;&lt;/script&gt; 或 liferay-portlet.xml

我下载多文件的脚本是否正确?

<c:if test="<%= multi_files_urls != null && multi_files_urls.size() > 1 %>">
    <aui:button onClick="downloadFiles(<%= multi_files_urls %>)" value="Download files"></aui:button>
</c:if>

<script type="text/javascript">
 function downloadFiles(multi_files_urls) {
     for (var url in multi_files_urls )
        JSZipUtils.getBinaryContent(url, function(err, data) {
        if(err) {
            throw err;
        }
        JSZip.loadAsync(data).then(function () {
         var zip = new JSZip(data);
            });
        });

     zip.then(function(content) {
            saveAs(content, "my_documents.zip");
    });
}
</script>

我收到以下错误:

(index):1 Uncaught ReferenceError: zip is not defined 在下载文件((索引):1) 在 HTMLInputElement.onclick ((index):1)

更新

我尝试了&lt;header-portlet-javascript&gt;/js/jszip.js&lt;/header-portlet-javascript&gt;&lt;script type="text/javascript" src="&lt;%=request.getContextPath()%&gt;/js/jszip.js"&gt;&lt;/script&gt;,但没有成功。

我点击了这个链接:Unable to include css and JS files in Liferay Portlet JSP Page

【问题讨论】:

    标签: javascript liferay liferay-6 jszip


    【解决方案1】:

    我没有检查,但看起来这完全独立于 Liferay 以及您如何嵌入代码:错误消息显示 zip is not defined。 定义zip 的唯一地方是在这个函数中,它立即超出范围:

     JSZip.loadAsync(data).then(function () {
        var zip = new JSZip(data);
     });
    

    因此,这段代码运行时不在作用域内:

     zip.then(function(content) {
        saveAs(content, "my_documents.zip");
     });
    

    您必须声明进一步向上压缩,以便在您想要使用它时它仍在范围内(但很可能,初始化它在您当前的位置初始化)。由于我没有使用 JSZip 库的经验并且使用了 async 关键字,我不确定仅重新排序是否足够,或者时间是否只会在其预期使用后初始化 zip - 我将把它留给你。

    尝试在单个 HTML 页面中重现,因为我不认为 Liferay 会给游戏带来的复杂性是导致问题的原因。这可能更容易理解。运行时,将其嵌入 Liferay。

    【讨论】:

      【解决方案2】:

      更新(解决方案)

      1- 我在 liferay-portlet.xml 文件中添加了 js 文件。

          <footer-portlet-javascript>/js/jquery-1.8.3.min.js</footer-portlet-javascript>
          <footer-portlet-javascript>/js/jszip.js</footer-portlet-javascript>
          <footer-portlet-javascript>/js/jszip-utils.js</footer-portlet-javascript>
          <footer-portlet-javascript>/js/FileSaver.js</footer-portlet-javascript>
          <footer-portlet-javascript>/js/downloader.js</footer-portlet-javascript>
          <footer-portlet-javascript>/js/helpers.js</footer-portlet-javascript>
      

      2- 在我看来.jsp

      <form action="#" id="download_form">
                      <% 
                          PortletURL actionURL = renderResponse.createRenderURL(); 
                          List<DLFileEntry> list = (List<DLFileEntry>) request.getAttribute("listFiles");
                          DateFormat dateFormat = new SimpleDateFormat("MMM yyyy");
                          
                          OrderByComparator orderByComparator = OrderByComparatorFactoryUtil.create("DLFileEntry", "modifiedDate", false);
                          Collections.sort(list,orderByComparator);
                      %>
      
                      <p class="hide" id="result"></p>
                      <aui:button id="download_files" type="submit" value="Download files"></aui:button>
      
                      <liferay-ui:search-container iteratorURL="<%= actionURL %>"
                          delta="10" emptyResultsMessage="no-documents">
                          <liferay-ui:search-container-results total="<%= list.size() %>"
                              results="<%= ListUtil.subList(list, searchContainer.getStart(), searchContainer.getEnd()) %>" />
                          <liferay-ui:search-container-row modelVar="file"
                              className="DLFileEntry">
                              <%
                                  ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
                                  String pdfUrl = "", excelUrl = "";
                                  String logo ="", vendor="", technology="", productType="", flashType="";
                                  
                                  long globalGroupId = GroupLocalServiceUtil.getCompanyGroup(PortalUtil.getDefaultCompanyId()).getGroupId();
                                  
                                  if(file.getExtension().equalsIgnoreCase("pdf"))
                                      pdfUrl = "<a target='_blank' href='"+ themeDisplay.getPortalURL() + themeDisplay.getPathContext() + "/documents/" + globalGroupId + StringPool.SLASH + file.getUuid()+"' ><img src='/flash-table-portlet/images/pdf.png' width='20px'/> </a>";
                                  else if(file.getExtension().equalsIgnoreCase("xlsx") || file.getExtension().equalsIgnoreCase("xls") || file.getExtension().equalsIgnoreCase("csv") )
                                      excelUrl = "<a target='_blank' href='"+ themeDisplay.getPortalURL() + themeDisplay.getPathContext() + "/documents/" + globalGroupId + StringPool.SLASH + file.getUuid()+"' ><img src='/flash-table-portlet/images/excel.png' width='20px'/> </a>";
          
                                  try{
                                      Map<String, Fields> fieldsMap = file.getFieldsMap(file.getFileVersion().getFileVersionId());
                                      for (Fields fields : fieldsMap.values()) {
                                          vendor =  fields.get("vendor").getValue().toString().replace("[\"", "").replace("\"]", "");
                                          if(vendor.equalsIgnoreCase("other"))
                                              logo="<strong>other</strong>";
                                          else
                                              logo = "<img src='/flash-table-portlet/images/vendor/"+vendor.toLowerCase()+".gif' style='max-width:120px' />";
                                          technology= fields.get("technology").getValue().toString().replace("[\"", "").replace("\"]", "");
                                          productType =  fields.get("producttype").getValue().toString().replace("[\"", "").replace("\"]", "");
                                          flashType =  fields.get("flashtype").getValue().toString().replace("[\"", "").replace("\"]", "");
                                      }
                                  }catch(Exception ex){
                                      ex.printStackTrace();
                                  }
                              %>
      
                              <%! String file_name = ""; %>
      
                              <%
                                  String fileUrl = themeDisplay.getPortalURL() + themeDisplay.getPathContext() + "/documents/" + globalGroupId + StringPool.SLASH + file.getUuid();
                                  file_name = file.getTitle() + "." + file.getExtension();
                               %>
      
                              <liferay-ui:search-container-column-text name="Checkbox">
                                  <input type="checkbox" data-url="<%= fileUrl %>"
                                      name="<%= file_name %>" />
                              </liferay-ui:search-container-column-text>
                              <liferay-ui:search-container-column-text name='date'
                                  cssClass="txt-capitalize width-10"
                                  value="<%= dateFormat.format(file.getModifiedDate()) %>" />
                              <liferay-ui:search-container-column-text name='vendor'
                                  cssClass="width-10" value="<%= logo %>" />
                              <liferay-ui:search-container-column-text name='technology'
                                  cssClass="width-10" value="<%= technology %>" />
                              <liferay-ui:search-container-column-text name='product-type'
                                  cssClass="width-12" value="<%= productType %>" />
                              <liferay-ui:search-container-column-text name='flash-type'
                                  cssClass="width-12" value="<%= flashType %>" />
                              <liferay-ui:search-container-column-text name='model'
                                  cssClass="width-25" value="<%= file.getTitle() %>" />
                              <liferay-ui:search-container-column-text name='executive-summary'
                                  cssClass="width-10" value="<%= pdfUrl %>" />
                              <liferay-ui:search-container-column-text name='excel-file'
                                  cssClass="width-10" value="<%= excelUrl %>" />
                          </liferay-ui:search-container-row>
                          <liferay-ui:search-iterator
                              searchContainer="<%= searchContainer %>"
                              paginate="${fn:length(listFiles) ge 10}" />
                      </liferay-ui:search-container>
                  </form>
      

      一切正常!

      【讨论】:

      • 您愿意解释一下这个解决方案背后的原理吗?很难从完整的 jsp 中获得它的要点,最好只发布最小版本。这样,其他人也可能会在此答案中找到价值。另外:看起来这也消除了your other question
      • 这个问题【为什么searchContainer变量是未知的? ] (stackoverflow.com/questions/46811395/…) 仍在等待中。
      猜你喜欢
      • 2018-03-29
      • 2014-01-17
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      相关资源
      最近更新 更多