我正在恢复服务的客户端工作,让用户下载文件。我确实可以访问服务器端代码。
客户端在Struts 2下,并提交了一些带有XML的POST请求,并且在处理该XML后,服务器(在Spring下)将生成zip文件的字节数组表示。
我的问题是如何将字节数组作为某些InputStream
传输,这是Struts 2的下载所要求的。
客户端使用Struts 2,这是struts.xml
中的配置,用于下载文件
<action name="getResponseMessage"
class="DownloadAction"
method="retrieveDownloadableMessage">
<interceptor-ref name="logger" />
<interceptor-ref name="defaultStack" />
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${bundleName}"</param>
<param name="bufferSize">1024</param>
</result>
</action>
在Java Action类中使用泽西岛(有HTTP状态检查和适当的字段getters,我为简单起见。):
public class DownloadAction extends ActionSupport {
private InputStream inputStream;
private String bundleName;
public String retrieveDownloadableMessage() throws IOException {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
URI restfulURI = getRestfulURI();
WebResource resource = client.resource(restfulURI);
inputStream = resource.accept(MediaType.APPLICATION_OCTET_STREAM).post(InputStream.class, someXML);
bundleName = "response.zip";
return SUCCESS;
}
}
REST服务器端代码的主干:
@POST
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes({ MediaType.APPLICATION_XML, MediaType.TEXT_XML })
public Response getPtrXml(Source source) throws IOException {
byte[] myByteArray = generateByteArr(source); // I cannot modify this method.
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(myByteArray);
return Response.ok(byteInputStream, MediaType.APPLICATION_OCTET_STREAM).build();
}
运行客户端代码,我看到了这样的控制台输出。似乎没有任何寄给客户的东西。有什么问题?
Streaming result [inputStream] type=[application/octet-stream] length=[0] content-disposition=[attachment;filename="${packagePtrName}"] charset=[null]
E WLTC0017E: Resources rolled back due to setRollbackOnly() being called.
E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[ServletNameNotFound]: java.lang.IllegalStateException: Response already committed.
更新:
Struts 2默默地将文件保存到temp
文件夹
我发现,如果我使用File
对象接受返回的ByteArrayInputStream
,然后Struts 2以某种方式将文件(正是我要寻找的内容)保存到本地temp
文件夹中,而无需向用户打开下载对话框。有什么想法如何挖出来?
File fileToDownload = resource.accept(MediaType.APPLICATION_OCTET_STREAM).post(File.class, someXML);
inputStream = new FileInputStream(fileToDownload);
您在返回客户端响应之前应该检查状态代码。由于您没有这样做,因此在阅读后,您无法返回输入流。
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
您可以从响应中获取输入流
inputStream = response.getEntityInputStream();
if (inputStream != null) {
//read it to make sure the data is available
您也没有为bundleName
提供公共Getter,并且您获得了${bundleName}
文件名。