Hi,
We're going to implement a download function which is triggered from the server side , the code would like:
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
// obtains response's output stream
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inStream.close();
outStream.close();
The question is : how can I get the HttpServletResponse with Java SDK ?
Regards,
Sean
From some examples in the Thingworx extension development user guide, we know that: The HttpServletRequest/HttpServletResponse parameter class is part of the javax.servlet third-party JAR which must be in the build path for the custom code to compile.
So you need to add this Jar to the library by yourself and import "javax.servlet.http.HttpServletResponse" to your own class.
@yhan ,
I know it's part of javax.servlet, and I can added to the build path/classpath. But how can I get the instance of HttpServertResponse in a Java extension ?
For example,
I can defined a Java method in the subclasss of Thing or :
public void DownloadFile(Byte[] content, HttpServletResponse response){
//write output stream to response for download
}
But how can I get the response object ? by adding certain annotation or getting it from certain context object ?
Regards,
Sean
I'm not sure if there is an easier way in thingworx extension development, but obviously you can map a servlet filter in the web.xml file.
@yhan ,
yes, but I want it to be a general download helper Thing in ThingWorx. It can be called by any other things, for example , ThingA reads file from FileRepository and then call the download helper Thing to download it (popup a download dialog in browser) .
Is it possible ?
Regards,
Sean
You can use the Service GetFileListingWithLinks, it will give you a hyperlink(like http://xxxx:8080/Thingworx/FileRepositories/SystemRepository/example.txt ) to allow the file to be download.
We just need to call this service from SDK, below code is a sample:
//A ValueCollection is used to specify a service's parameters
ValueCollection params = new ValueCollection();
params.put("path", new StringPrimitive("/"));
params.put("nameMask", new StringPrimitive("example.txt"));
// Use the SystemRepository Thing to get the file URL.
client.invokeService(ThingworxEntityTypes.Things, "SystemRepository",
"GetFileListingWithLinks", params, 15000);
//it is returned within an InfoTable and you can get the URL from the result.
params.clear(); // Clear the params used in the previous service invocation.
Also, the URL can be passed to another method based on your code logic.