Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define the output name of a StreamResult in Struts2?

Tags:

java

struts2

Guys, I cant find this info clearly in the web. I have an action and I'm generating a text file, however is always appearing to the client as a "generatePDF.action" file. I want it to show as a receipt.txt file.

Here is my annotation:

   @Action(value = "/generateTXT",
    results = {
        @Result(name = "ok", type = "stream",
        params = {"inputName", "inputStream",
                  "contentType", "application/octet-stream",
                  "contentDispostion", "attachment;filename=receipt.txt"})
    })
like image 342
Marcos Roriz Junior Avatar asked Dec 12 '10 23:12

Marcos Roriz Junior


1 Answers

If you are using the conventions plug-in then lets use the following code for reference runs under "/YourApplicationContext/stream/stream-test" which then resolves to "/YourApplicationContext/stream/document.txt":

package struts2.stream;

import com.opensymphony.xwork2.ActionSupport;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import org.apache.struts2.convention.annotation.Result;


@Result(name = ActionSupport.SUCCESS, type = "stream", params =
{
    "contentType",
    "text/hmtl",
    "inputName",
    "inputStream",
    "contentDisposition",
    "filename=document.txt"
})
public class StreamTestAction extends ActionSupport{
    public InputStream inputStream;

    @Override
    public String execute(){
    inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action.");      
    return SUCCESS;
    }
}

Please take note of "contentDisposition" and that its value has been set to "filename='document.txt'" changing 'document.txt' gets you what you want.

like image 126
Quaternion Avatar answered Oct 31 '22 16:10

Quaternion