您的位置:首页 > 编程语言 > Java开发

java web项目下载代码例子

2015-12-15 11:24 459 查看
java web项目下载代码例子:

1.新建工具类:DownlaodUtils.java

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownlaodUtils {

/**
* 生成txt文件
* @param fileName	txt路径
* @param fileContent	写入内容
*/
public static void writeFile(String fileName, String fileContent)
{
try
{
File f = new File(fileName);
if (!f.exists())
{
f.createNewFile();
}
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"gbk");
BufferedWriter writer=new BufferedWriter(write);
writer.write(fileContent);
writer.close();
} catch (Exception e)
{
e.printStackTrace();
}
}

/**
* 打包文件下载
* @param files 下载文件集合
* @param request
* @param response
* @return
* @throws Exception
*/
public static HttpServletResponse downLoadFiles(List<File> files,
HttpServletRequest request, HttpServletResponse response,String filepash)
throws Exception {
try {
/**这个集合就是你想要打包的所有文件,
* 这里假设已经准备好了所要打包的文件*/
//List<File> files = new ArrayList<File>();

/**创建一个临时压缩文件,
* 我们会把文件流全部注入到这个文件中
* 这里的文件你可以自定义是.rar还是.zip*/
File file = new File(filepash);
if (!file.exists()){
file.createNewFile();
}
response.reset();
//response.getWriter()
//创建文件输出流
FileOutputStream fous = new FileOutputStream(file);
/**打包的方法我们会用到ZipOutputStream这样一个输出流,
* 所以这里我们把输出流转换一下*/
//            org.apache.tools.zip.ZipOutputStream zipOut
//                = new org.apache.tools.zip.ZipOutputStream(fous);
ZipOutputStream zipOut
= new ZipOutputStream(fous);
/**这个方法接受的就是一个所要打包文件的集合,
* 还有一个ZipOutputStream*/
zipFile(files, zipOut);
zipOut.close();
fous.close();
return downloadZip(file,response);
}catch (Exception e) {
e.printStackTrace();
}
/**直到文件的打包已经成功了,
* 文件的打包过程被我封装在FileUtil.zipFile这个静态方法中,
* 稍后会呈现出来,接下来的就是往客户端写数据了*/
// OutputStream out = response.getOutputStream();

return response ;
}

/**
* 把接受的全部文件打成压缩包
* @param List<File>;
* @param org.apache.tools.zip.ZipOutputStream
*/
@SuppressWarnings("rawtypes")
public static void zipFile(List files,ZipOutputStream outputStream) {
int size = files.size();
for(int i = 0; i < size; i++) {
File file = (File) files.get(i);
zipFile(file, outputStream);
}
}

public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {
try {
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}finally{
try {
File f = new File(file.getPath());
f.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}

/**
* 根据输入的文件与输出流对文件进行打包
* @param File
* @param org.apache.tools.zip.ZipOutputStream
*/
public static void zipFile(File inputFile,
ZipOutputStream ouputStream) {
try {
if(inputFile.exists()) {
/**如果是目录的话这里是不采取操作的,
* 至于目录的打包正在研究中*/
if (inputFile.isFile()) {
FileInputStream IN = new FileInputStream(inputFile);
BufferedInputStream bins = new BufferedInputStream(IN, 512);
//org.apache.tools.zip.ZipEntry
ZipEntry entry = new ZipEntry(inputFile.getName());
ouputStream.putNextEntry(entry);
// 向压缩文件中输出数据
int nNumber;
byte[] buffer = new byte[512];
while ((nNumber = bins.read(buffer)) != -1) {
ouputStream.write(buffer, 0, nNumber);
}
// 关闭创建的流对象
bins.close();
IN.close();
} else {
try {
File[] files = inputFile.listFiles();
for (int i = 0; i < files.length; i++) {
zipFile(files[i], ouputStream);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}


2.action类

/**
* 下载功能
* @param condition2
* @return
* No such file or directory
*/
<span style="white-space:pre">	</span>@Action(value="/downloadfile")
private String downlaodfile(String conditions) {
HttpServletRequest request = ServletActionContext.getRequest();
//		HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
session.setAttribute("bizno",conditions);
return "下载成功-";
}
@Action(value="/downloadfi")
public String nxDownload(){
HttpServletRequest request = ServletActionContext.getRequest();
HttpSession session = request.getSession();
HttpServletResponse response = ServletActionContext.getResponse();

String bizno=(String)session.getAttribute("bizno");

response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=UTF-8");
//下载所需文件路径
String path=request.getSession().getServletContext().getRealPath("/");

String filenames=path+"wondlaod/"+bizno+".txt";
File file=new File(filenames);    
if(!file.exists()) DownlaodUtils.writeFile(filenames," \r\n 生产地址:"+GetProValue.getPro("hosturl")+"\r\n 商户编号:"+bizno);

List<File> list=new ArrayList<File>();
File file3=new File(path+"key/"+bizno+GetProValue.getPro("bftpubcerpathname"));
File file1=new File(path+"key/"+bizno+GetProValue.getPro("merprijkspathname"));
File file2=new File(path+"wondlaod/"+bizno+".txt");
list.add(file3);
list.add(file1);
list.add(file2);
try {
DownlaodUtils.downLoadFiles(list,request,response,path+bizno+".rar");
} catch (Exception e) {
System.out.println("进入catch模块");
}

return null;
}


3.js

/**
* 下载证书
*/
function downlaodzh(){
var gl15 = $("#submit_cc").combobox("getText");
if(gl15 == ''){$.messager.alert('提示','一级商户号为必选项!'); return false; }
if(gl15 == '请选择') {$.messager.alert('提示','一级商户号为必选项!'); return false; }
if(gl15.indexOf("/")>=0) gl15=gl15.substring(gl15.lastIndexOf('/')+1);
$.ajax({
url : 'submitmanage.do?data=0014!'+encodeURIComponent(gl15),
type : 'GET',
timeout : 15000,
async : true,
cache : false,
success : function(data) {//返回结果
var arr=data.isTrue.split("-");//分拆字符串为数据
if(arr[0] == "0"){//下标0位置的值为0表示查询失败
$.messager.alert('提示',arr[1]);
}else if(arr[0] == "1"){
$.messager.confirm('提示', '您已长时间未使用系统或由于系统原因,请重新登录!', function(r){
if (r) {
relogin();
}
});
}else{//否则表示查询成功

downloadFile("http://localhost:18083/w_authen/downloadfi.do");

}
},
error : function(data) {
//提示并隐藏加载效果
$.messager.alert('提示','系统异常!');
}
});

}

function downloadFile(url) {
try{
var elemIF = document.createElement("iframe");
elemIF.src = url;
elemIF.style.display = "none";
document.body.appendChild(elemIF);
}catch(e){

}
}


注明:在web项目里有关下载最容易遇到的一个错误:   java.lang.IllegalStateException

造成这个错误的原因是:该异常表示,当前对客户端的响应已经结束,不能在响应已经结束后再向客户端(缓冲区)输出任何内容。

     即Servlet规范说明,不能调用 response.getOutStream(),又调用response.getWriter(),无论先调用哪一个,在调用第二个时候应会抛出          
             IllegalStateException,因为在js中,out变量是通过response.getWriter得到的,在程序中即用了response.getOutputStream,又用了out变量,故      出现以上错误。

   故此我给出的例子,就是在写下载的时候,通过2次不同的请求到下载action以达到传数据给服务器的同时,又可以达到下载效果,方法也许不够好,但希望能帮助遇到下载问题的朋友。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java javascript