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 alw开发者_如何学Goays 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.
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 :-)
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.
精彩评论