简体   繁体   中英

How can I define the output name of a StreamResult in 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"})
    })

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.

My annotation is basically the same, but I used a reference to set file's name:

@Result(name="export", type="stream",
   params={ "contentType", "application/octet-stream",
    "inputName", "fileInputStream",
    "contentDisposition", "attachment;filename=%{exportFilename}",
    "bufferSize", "4096"})

exportFilename is a String variable with getter and setter and it can also be put at a inheritable class, so it is possible to create an unique ExportAction and make all actions extend it.

Probably you can create variables to set all parameters' values.

The original annotation is fine, it only contains a typo:

"contentDispostion" should read "contentDisposition"

I took me ages to figure this out, so I thought I'd make it clear :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM