本程序是通过java和struts2先实现把文件上传到服务器或者是存储到硬盘,然后把该文件下载下来:
一:首先是struts2配置文件:result返回类型一定要写成type=”stream”
<package name=”download” extends=”struts-default”>
<action name=”download_*” class=”upload.action.FileDownload” method=”{1}”>
<result name=”success” type=”stream”>
<param name=”contentType”>text/plain</param>
<param name=”contentDisposition”>attachment;fileName=”${fileName}”</param>
<param name=”inputName”>downloadFile</param>
<param name=”bufferSize”>1024</param>
</result>
</action>
</package>
二:然后是action类:
package upload.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
//文件下载
public class FileDownload extends ActionSupport{
private static final long serialVersionUID = 1L;
private String fileName;
private int number;
public InputStream getDownloadFile() throws Exception{
int number=1;
//从这是把数据写入到文档中——- 开始
String str=”afsdasdfasdfadfaaaaaaaaaaaaaaafasdfasdfasdfasfasdfasdfasdf!”;
File txt=new File(“D:/attachment/report/Test.txt”);
if(!txt.exists()){//如果不存在就创建一个文件
txt.createNewFile();
}
byte bytes[]=new byte[512];
bytes=str.getBytes();
int b=str.length();
FileOutputStream fos=new FileOutputStream(txt);
fos.write(bytes,0,b);//通过流写入硬盘
fos.close();
//从这是把数据写入到文档中——- 结束
//从这是把上面存到硬盘的文件下载下来——– 开始
String path = “D:/attachment/”;
//if(number == 1){
path += “report/”;
//}
// String aId = ServletActionContext.getRequest().getParameter(“attachId”);//保存的id
//List<Attachment> attaList = attachmentService.findAttachmentById(aId);
//Attachment attachment = attaList.get(0);
//String aName=attachment.getGeneratedfilenamedirectory();
String aName=”Test.txt”;
//String fileName=attachment.getOriginalname();
String fileName=”Test.txt”;
// 如果下载文件名为中文,进行字符编码转换
ServletActionContext.getResponse().setHeader(“Content-Disposition”,”attachment;fileName=”+ new String(fileName.getBytes(“gb2312”), “ISO8859-1” ));
File file = new File(path+aName);
if(!file.exists()){
return null;
}
InputStream inputStream = new FileInputStream(file);
return inputStream;
//从这是把上面存到硬盘的文件下载下来——– 结束
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
}
三:action调用,在前台直接写action地址:
window.location.href=”${pageContext.request.contextPath }/download_execute.action;
转载请注明来源网站:blog.ytso.com谢谢!
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/14705.html