文件能上传当然也能下载了,下面是一个下载文件的例子,万变不离其宗,所以对于其他文件的下载,只要改变一些参数和配置就可以了。
以下代码都是可以运行的。
这是jsp页面的部分代码:
<</span>form action="${pageContext.request.contextPath}/ttt/downlord.action">
文件路径:<</span>input type="text" name="inputPath" value="/uploads/test.zip"/><</span>br/>
文件名称:<</span>input type="text" name="fileName" value="test.zip"/><</span>br/>
<</span>input type="submit" value="下载"/><</span>br/>
</</span>form>
这是文件下载的Action:
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadFile extends ActionSupport {
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
private String inputPath;
private String fileName;
public InputStream getInputStream() throws Exception{
return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
}
@Override
public String execute() throws Exception {
if(!inputPath.startsWith("/WEB-INF")){
return SUCCESS;
}
return null;
}
public String getDownloadFileName(){
String downFileName=fileName;
try {
downFileName=new String(downFileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return downFileName;
}
}
这是文件下载的配置文件:
<</span>action name="downlord" class="com.defu.com.DownloadFile">
<</span>result name="success" type="stream">
<</span>param name="contentType">application/octet-stream;charset=ISO8859-1</</span>param>
<</span>param name="inputName">inputStream</</span>param>
<</span>param name="contentDisposition">attachment;filename=${downloadFileName}</</span>param>
<</span>param name="bufferSize">4096</</span>param>
</</span>result>
</</span>action>
当然,文件下载也可能是其他文件类型,只要改变一些红色的
contentType
中的参数就可以了。