文件下载

/**
	 * 下载文件

	 */
	public ActionForward downLoad(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String destPathName = servlet.getServletContext().getRealPath("/");
		response.reset();
		String fileName = request.getParameter("fileName");
		String filePath = request.getParameter("filePath");
		filePath = destPathName + "/" + filePath;
		int index = fileName.lastIndexOf(".");
		String savename = fileName.substring(0, index);
		String hz = fileName.substring(index + 1, fileName.length());
		// response.setCharacterEncoding("GBK");
		//response.setContentType("application/OCTET-STREAM");
//不禁用页面缓存,使文件可以直接打开
		response.setHeader("Pragma", "");
		response.setHeader("Cache-Control", "");
		response.setContentType("application/x-msdownload");
		// response.setContentType("application/ms-excel;charset=GBK");
		response.setHeader("Content-Disposition", "attachment;   filename=\""
				+ toUtf8String(savename) + "." + hz);

		ServletOutputStream sos = response.getOutputStream();
		InputStream is = new java.io.FileInputStream(filePath);

		int i = 0;
		while ((i = is.read()) != -1) {
			sos.write(i);
		}

		is.close();
		sos.close();
		sos.flush();
		return null;
	}

	// toUtf8String()对中文进行转换
	// 下载为中文名不会出现乱码
	private String toUtf8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}

你可能感兴趣的:(C++,c,Excel,C#,J#)