天天看點

從伺服器下載下傳檔案 根據絕對路徑下載下傳檔案 --java

從伺服器上下載下傳檔案

根據絕對路徑下載下傳檔案

/**
	 ** 檔案下載下傳
	 *@author jiejing
	 *
	 * / 
	 */
	@ResponseBody
	@RequestMapping("/dadown")
	public void dadown(Integer did,String loginname,HttpServletResponse response,HttpServletRequest request){
		Qdatum dadown = datumServiceImpl.dadown(loginname,did);
		String durl = dadown.getDurl();//得到檔案存儲路徑
		String dtitle = dadown.getDtitle();檔案檔案名稱
		DataDown d = new DataDown();
			try {
				d.downauthimg(durl, dtitle,null,null);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	}
	
           

下載下傳工具類方法:

public HttpServletResponse download(String path,String dtitle, HttpServletResponse response,HttpServletRequest request) {
	        try {
	            // path是指欲下載下傳的檔案的路徑。
	            File file = new File(path);
	            // 取得檔案名。
	            String filename = dtitle;
	           //filename = new String(filename.getBytes(), "ISO-8859-1");
	           // filename = URLEncoder.encode(filename, "UTF-8");
	           // response.setHeader("Content-Disposition","attachment;filename="+filename);
	            // 取得檔案的字尾名。
	            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

	            // 以流的形式下載下傳檔案。
	            InputStream fis = new BufferedInputStream(new FileInputStream(path));
	            byte[] buffer = new byte[fis.available()];
	            fis.read(buffer);
	            fis.close();
	            // 清空response
	            response.reset();
	            // 設定response的Header
	            //解決獲得中文參數的亂碼問題----
	            //filename = new String(filename.getBytes("ISO8859-1"),"UTF-8");//美女.jpg

	           // response.addHeader("Content-Disposition", "attachment;filename=" + filename);
	            response.addHeader("Content-Disposition", "attachment;filename="
	            		+ new String(filename.getBytes("utf-8"), "ISO-8859-1"));
	            response.addHeader("Content-Length", "" + file.length());
	            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	            response.setContentType("application/octet-stream");
	            toClient.write(buffer);
	            toClient.flush();
	            toClient.close();
	        } catch (IOException ex) {
	            ex.printStackTrace();
	        }
	        return response;
	    }