---
title: "Java 下载Oracle中Blob数据"
author: "sam_chen"
date: "2012-11-20T11:01:32Z"
tags: []
categories: ["编程语言"]
slug: "java-oracle-blob"
draft: false
lastmod: "2012-11-20T11:01:32Z"
id: 1730456
url: "https://sam-chen.iteye.com/blog/1730456"
---

public int downloadFile(HttpServletRequst req, HttpServletResponse response )
			throws Exception {
		long infoPageAttachId = req.getParameter("infoPageAttachId", 0L);
		if (infoPageAttachId == 0L) {
			return RETCODE_ERR;
		}
		TInfoPageAttach ipAtt = getService(TInfoPageAttachService.class)
				.getById(infoPageAttachId);

		String filename = ipAtt.getFileName();
		response.setContentType("application/x-download");
		response.setCharacterEncoding("UTF-8");
		response.addHeader("Content-Disposition", "attachment;filename="
				+ URLEncoder.encode(filename, "UTF-8"));
		Blob blob = ipAtt.getFileContent();

		InputStream ins = blob.getBinaryStream();
		// 用文件模拟输出流
		OutputStream fout = response.getOutputStream();
		try {
			// 下面将BLOB数据写入文件
			byte b = new byte;
			int len = 0;
			while ((len = ins.read(b)) != -1) {
				fout.write(b, 0, len);
				fout.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			fout.close();
			ins.close();
		}
		return RETCODE_OK;
	}