javaweb實現附件下載 如:txt,png,jpg等

/**
	 * springMVC文件下載 (txt,png等格式)
	 * @param request
	 * @param response
	 * @throws Exception 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(params="method=downloadFile",method=RequestMethod.GET)
	public void downloadFile(HttpServletRequest request,HttpServletResponse response) throws Exception{
		ServletContext sc  = request.getSession().getServletContext();
		String path = request.getParameter("path");
		String fileName = request.getParameter("fileName");
		if(!fileName.contains(".")){
			if(StringUtils.isNotBlank(path)){
				fileName= fileName+"." +path.split("\\u002E")[1];
			}
		}
		String filePath =sc.getRealPath(path);
		File file =  new File(filePath);
		if(!file.exists()){
			throw new Exception("文件不存在!");
		}
		try {
			FileInputStream in = new FileInputStream(file);
			response.setHeader("content-disposition", "attachment;filename=" +URLEncoder.encode(fileName, "UTF-8"));
			OutputStream out =response.getOutputStream();
			byte buffer[] = new byte[1024];
			int len = 0;
			while((len=in.read(buffer))>0){
				out.write(buffer, 0, len);
			}
			//關閉文件輸入流
			in.close();
			//關閉輸出流
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

注意事項:java

1,ajax請求無效。ajax

相關文章
相關標籤/搜索