文档服务器文件下载

文件下载:封装方法

这个方法为从其他的文档服务器进行文件的下载,不能使用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();
		}
	
	}

}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FastStone Capture 是一款出色的屏幕捕捉(截图)软件,它集图像捕捉、浏览、编辑、视频录制等功能于一身,功能完善、使用方便,值得推荐! 软件提供多种捕捉方式(如:活动窗口、指定窗口/对象、矩形区域、手绘区域、整个屏幕、滚动窗口等),提供屏幕录像机、放大镜、拾取颜色、标尺等辅助功能,支持快捷键操作 对于捕捉到的图像,软件提供了多种处理方式,如:在编辑器打开;存入剪贴板或文件;发送到打印机、邮件、WORD、Powerpoint 甚至是网络 FTP 等。用户还可以通过文件名称模板定制文件名以自动保存捕捉内容,支持BMP、GIF、JPG、PNG、TIF、PDF等文件格式,输出文件夹位置也可以自行设定。 软件内置功能完善的图像编辑器,支持几乎所有主流图片格式,除提供缩放、旋转、剪切、格式转换、调整大小等基本功能外,还可向图像中加入标题、边框和水印、文本、线条、图形等内容,并可调整图像颜色,进行多种特效处理。 二、版本特色 本版本基于官方英文原版汉化,集成注册文件,并优化了部分设置。相对于其他版本,具有更新及时、汉化彻底、使用方便等特点。希望大家喜欢! FastStone Capture 7.7 更新日志: - 现在,您可以使用拖放和拖放移动(复制时Ctrl和向下键)选择区域 - 增加了两个新的选择方法 - 编辑器的菜单栏上添加撤消/重做按钮 - 添加聚光灯效果 - 许多小的改进和错误修正
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值