我正在尝试将Java servlet中的zip文件发送到JavaScript客户端。我首先在磁盘上生成zip存档,然后尝试将其发送到客户端。拉链生成工作正常。但是,我将它发送给客户端时遇到了问题。
与将文件发送到客户端(doPost
内)相关的代码如下:
String path = getServletContext().getRealPath("/") + "generatedApps/";
String fileName = appName + "Archive.zip";
File f = new File(path + fileName);
response.setContentType("application/zip");
response.setContentLength((int)f.length());
response.addHeader("Content-Encoding", "gzip");
response.addHeader("Content-Disposition","attachment;filename=\"" + fileName + "\"");
byte[] arBytes = new byte[(int)f.length()];
FileInputStream is = new FileInputStream(f);
is.read(arBytes);
ServletOutputStream op = response.getOutputStream();
op.write(arBytes);
op.flush();
这是来自客户端的Ajax请求:
new Ajax.Request( source, {
asynchronous: false,
method: 'post',
parameters: {content: RWSMLFile},
onSuccess: function(transport){
console.log(transport);
}.bind(this),
onFailure: (function ( transport ) {
ORYX.Log.error( "Sending RWSML file failed! Info: " + transport );
}).bind( this )
} );
在浏览器控制台中,我收到以下错误:
POST http://localhost:8080/oryx/generategeddyjscode prototype-1.5.1.js:1044
Ajax.Request.Object.extend.request prototype-1.5.1.js:1044
Ajax.Request.Object.extend.initialize prototype-1.5.1.js:1006
(anonymous function) prototype-1.5.1.js:37
ORYX.Plugins.RWSMLSupport.ORYX.Plugins.AbstractPlugin.extend.generateGeddyJsCode rwsmlSupport.js:47
(anonymous function) prototype-1.5.1.js:105
a.each.j.functionality default.js:2828
Ext.Button.Ext.extend.onClick ext-all.js:87
V ext-all.js:13
O
如果我转到Source
标签,那么我会在以下代码段的最后一行之后得到Failed to load resource
:
if (this.options.onCreate) this.options.onCreate(this.transport);
Ajax.Responders.dispatch('onCreate', this, this.transport);
this.transport.open(this.method.toUpperCase(), this.url,
this.options.asynchronous);
if (this.options.asynchronous)
setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);
this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();
this.body = this.method == 'post' ? (this.options.postBody || params) : null;
this.transport.send(this.body);
我该如何解决这个问题?
答案 0 :(得分:4)
您需要使用返回码FileInputStream.read()
检查已写入的字节数。尝试这样的事情:
String path = getServletContext().getRealPath("/") + "generatedApps/";
String fileName = appName + "Archive.zip";
File f = new File(path + fileName);
response.setContentType("application/zip");
response.setContentLength((int)f.length());
response.addHeader("Content-Disposition","attachment;filename=\"" + fileName + "\"");
byte[] arBytes = new byte[32768];
FileInputStream is = new FileInputStream(f);
ServletOutputStream op = response.getOutputStream();
int count;
while ((count = is.read(arBytes)) > 0)
{
op.write(arBytes, 0, count);
}
op.flush();
修改强>
删除了从问题中复制的response.addHeader("Content-Encoding", "gzip");
。这是错的。