Struts 2中的文件下载将无法启动

时间:2018-04-27 03:47:50

标签: javascript java jquery download struts2

我有以下struts代码。我正在尝试下载一个csv文件,但是当我点击下载时没有任何反应。我没有得到任何错误,在JavaScript中我得到了成功的回复。 Myy post功能也会在浏览器控制台上记录我的csv内容。我不明白为什么文件下载不会开始下载。

这是我的jsp:

<%@ taglib prefix="s" uri="/struts-tags"%>
<div>
    <div>


    <h4>Information</h4>
        <div class="tab-pane" id="login">
                <div class="panel panel-default">
                    <form id = "info" class="form-horizontal">
                        <div >
                            <label>FName</label>
                            <span style="float:right"><s:property value="%{fName}" 
     </span>

                        </div>
                        <div>
                            <label>MName or Initial</label>
                            <span style="float:right"><s:property value="%{mName}"/></span>

                        </div>  
                        <div>
                            <label>LName</label>
                            <span style="float:right"><s:property value="%{lName}"/></span>

                        </div>  
                </form>
            </div>
        </div>
        </div>
        <div class="footer">
              <button type="button" class="btn btn-primary" onClick="download();">Download</button>          
            </div>
    </div>



    <script>
    function download(){
        var action = 'download.action';
        var meth = 'post';
        var fields = jQuery("#info").children();
        var params = [];
        for(var i=0; i<fields.length;i++){
            var field = fields[i];
            var nodes = jQuery(field).children();
            if(nodes.length == 2){
                params.push(encodeURIComponent(nodes[0].innerText)
                        +"="+
                        encodeURIComponent(nodes[1].innerText)); 
            }
        }
        var encr = btoa(params.join('&'));
        jQuery.post(action,"data="+encr,function(data,status,xhr){
            console.log(data);
            console.log(status);
            console.log(xhr);
        });

    }
    </script>

动作类

public class Downloads extends CustomActionClass{

   private static final long serialVersionUID = 1L;
   private String data;
   private InputStream fileStream;
   private long contentLength;


    public String execute() {
        String decodeData = new 
        String(java.util.Base64.getDecoder().decode(data));
    List<String> downloadData = new ArrayList<String>();
    try {
             String fileName = "info.csv";
        String [] dataList = URLDecoder.decode(decodeData,"UTF-8").split("&");
             String header ="";
                 String vals = "";
                 for(String dat: dataList) {
                     String[] tData = dat.split("=");
                     header += tData[0] + ",";
                     if(tData.length>1)
                         vals += tData[1]+",";
                 }

                 if(StringUtils.isNotBlank(header))
                     downloadData.add(header.substring(0,header.length()-1));
                 if(StringUtils.isNotBlank(vals))
                     downloadData.add(vals.substring(0,vals.length()-1));

                 File fil = new File(getServerTempFolder()+fileName);
                 fil.createNewFile();
                 contentLength = fil.length();
                 FileUtils.writeLines(fil, "UTF-8", downloadData);
                 fileStream =  new FileInputStream(fil);

            } catch (Exception e) {
                log.info("Error: " + e.getMessage());
                log.debug(e.fillInStackTrace());
            }       
    return SUCCESS;
}

        /**
         * @return the data
         */
        public String getData() {
            return data;
        }

        /**
         * @param data the data to set
         */
        public void setData(String data) {
            this.data = data;
        }

        /**
         * @return the fileStream
         */
        public InputStream getFileStream() {
            return fileStream;
        }

        /**
         * @param fileStream the fileStream to set
         */
        public void setFileStream(InputStream fileStream) {
            this.fileStream = fileStream;
        }

        /**
         * @return the contentLength
         */
        public long getContentLength() {
            return contentLength;
        }

        /**
         * @param contentLength the contentLength to set
         */
        public void setContentLength(long contentLength) {
            this.contentLength = contentLength;
        }

    }

这是我的Struts Mapping:

<action name="download" class="com.util.Downloads">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="contentLength">${contentLength}</param>
<param name="inputName">fileStream</param>
<param name="contentDisposition">attachment;filename="info.csv"</param>
<param name="bufferSize">1024</param>

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。因此,解决方法是ajax调用不会触发下载,因为它是发布请求。我不得不做window.href=action;这使得get调用,因此从流程类返回了流。

如果有人遇到编码问题,我会更进一步。要正确编码以便pdf写入正确的标头以指定UTF-8编码..对于csv,在开始将数据写入文件之前将其写入文件byte[] enc = new byte[] { (byte)0xEF, (byte)0xBB, (byte)0xBF };。是的,您可以编写此字节流,然后将String数据写入文件。

请参阅此链接以了解CSV http://smallbusiness.chron.com/utf8-encoding-excel-using-java-47939.html ...