文件下载:封装方法
这个方法为从其他的文档服务器进行文件的下载,不能使用file = new file(url); 的方法。需要 URL httpUrl=new URL(url);
conn=(HttpURLConnection) httpUrl.openConnection();进行数据的连接来进行文档的下载。
/**
* 文件下载 : 接口文件下载
* @param url 接口地址
* @param fileName 附件名称
*/
public void exportWord(HttpServletRequest request, HttpServletResponse response,
String url,String fileName){
InputStream fin = null;
OutputStream out = null;
InputStream inputStream = null;
HttpURLConnection conn = null;
try {
// 建立链接
URL httpUrl=new URL(url);
conn=(HttpURLConnection) httpUrl.openConnection();
//以Post方式提交表单,默认get方式
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
//连接指定的资源
conn.connect();
//获取网络输入流
inputStream = conn.getInputStream();
String codedFileName = encodingFileName(fileName);
response.setHeader("content-disposition", "attachment;filename="+ codedFileName);
fin = new BufferedInputStream(inputStream);
out = response.getOutputStream();
byte[] buffer = new byte[4096]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
while((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
inputStream.close();
fin.close();
conn.disconnect();
out.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
ZIP下载:
/**
* 附件ZIP下载
* @param url 接口地址
* @param fileName 附件名称
* urls : Map<String, String> MAP fileName: 文件名称, fileUrl : 文件下载路径
*
*/
public void exportZip(HttpServletRequest request, HttpServletResponse response,
List<Map<String, String>> urls,String zipName){
ByteArrayOutputStream bos = null;
ZipOutputStream zos = null;
ServletOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
zos = new ZipOutputStream(bos);
for (int i = 0; i < urls.size(); i++) {
zos.putNextEntry(new ZipEntry(i + "/" + urls.get(i).get("fileName")));
byte[] bytes = downURL(urls.get(i));
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
}
String fileName = new String((zipName + ".zip").getBytes("UTF-8"),
"ISO8859-1");
zos.close();
response.setContentType("application/force-download");
response.addHeader("content-disposition", "attachment;filename="
+ fileName);
os = response.getOutputStream();
os.write(bos.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
os.close();
zos.close();
bos.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
/**
* 读取URL中结果集
*/
private byte[] downURL(Map<String, String> map) throws Exception {
byte[] data = null;
InputStream is = null;
HttpURLConnection conn = null;
URL url = new URL(map.get("fileUrl"));
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);
is = conn.getInputStream();
if (conn.getResponseCode() == 200) {
data = readInputStream(is);
} else {
data = null;
}
is.close();
conn.disconnect();
return data;
}
/**
* 读取流程
*/
private byte[] readInputStream(InputStream is) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
while ((length = is.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
baos.flush();
byte[] data = baos.toByteArray();
is.close();
baos.close();
return data;
}
/**
* 主要设置reponse 流的setheader时的名称
* @param fileName 需要下载的名称
* 就设置下载是在浏览器中弹出的文件名称
*/
public static String encodingFileName(String fileName) {
String returnFileName = "";
try {
returnFileName = URLEncoder.encode(fileName, "UTF-8");
returnFileName = StringUtils.replace(returnFileName, "+", "%20");
if (returnFileName.length() > 0) {
returnFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
returnFileName = StringUtils.replace(returnFileName, " ", "%20");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return returnFileName;
}
调用方法
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.hisense.smartroad.common.util.ExpWordUtil;
import com.hisense.smartroad.saf.responsibility.dao.ViewDocumentSendFileDao;
import com.hisense.smartroad.saf.responsibility.entity.ViewDocumentSendFile;
import com.hisense.smartroad.saf.responsibility.entity.ViewDocumentSendFileAtt;
@Controller
@RequestMapping("/expOaFile")
public class ExpOaFileController {
static final String METHOD_TYPE = "GET" ; //OA公文路径
static final String OA_URL = "http://10.60.5.19:9191/govdocumentmanager/" ; //OA公文路径
@Resource
private ExpWordUtil expWordUtil;
@Autowired
private ViewDocumentSendFileDao documentSendFileDao; //公文DAO
/**
* 下载文件
* @param request
* @param response
* @throws UnsupportedEncodingException
*/
@RequestMapping("/downLoadFile")
public void downLoadFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException{
HttpSession session = request.getSession();
session.setAttribute("state", null);
response.setContentType("application/msword");
String fileName = request.getParameter("fileName");
byte[] bytes = fileName.getBytes("ISO8859-1");
// 将bytes字节数据按照指定字符编码字符编码进行组装,组装为String
fileName = new String(bytes, "UTF-8");
String fileTrueName = request.getParameter("fileTrueName");
String downLoadFileName = fileTrueName.substring(0,6);
try{
String url = OA_URL + downLoadFileName +"/" + fileTrueName;
expWordUtil.exportWord(request, response, url, fileName);
} catch (Exception e){
e.printStackTrace();
}
}
/**
* 下载ZIP
* @throws UnsupportedEncodingException
*/
@RequestMapping("/downLoadFileZip")
public void downLoadFileZIP(HttpServletRequest request, HttpServletResponse response){
try {
String recordId = request.getParameter("recordId");
List<ViewDocumentSendFileAtt> documentSendFileAtts = new ArrayList<ViewDocumentSendFileAtt>();
String hql = "from ViewDocumentSendFile where recordId = ?" ;
ViewDocumentSendFile viewDocumentSendFile = documentSendFileDao.findUnique(hql,recordId);
if (viewDocumentSendFile == null ||"".equals(viewDocumentSendFile)) {
return;
}
List<Map<String, String>> urls = new ArrayList<Map<String, String>>();
Map<String,String> map = new HashMap<String,String>();
String title = viewDocumentSendFile.getDocumentSendFileTitle();//公文文件名称
String sendName = viewDocumentSendFile.getFileName(); //公文路径
map.put("fileName", title + ".doc");
map.put("fileUrl", OA_URL + sendName);
urls.add(map);
expWordUtil.exportZip(request, response, urls, urls.get(0).get("fileName"));
} catch (Exception e) {
e.printStackTrace();
}
}
}