/**
* 文件下载
*
* @param request
* @param response
* @param id
* @throws Exception
* @throws NumberFormatException
*/
private void downLoadFile(HttpServletRequest request, String id)
throws NumberFormatException, Exception {
Contracttemplate ct = contracttemplateService
.queryContracttemplateById(Integer.parseInt(id));
if (ct != null) {
byte[] blobSource = ct.getBlobSource();
ByteArrayInputStream bais = new ByteArrayInputStream(blobSource);
String uploadDir = request.getSession().getServletContext()
.getRealPath("/")
+ "\\WEB-INF\\static\\contract\\";
File fileDir = new File(uploadDir);
if (!fileDir.exists()) {
fileDir.mkdirs(); //创建目录
}
String uploadDirPath = request.getSession().getServletContext()
.getRealPath("/")
+ "\\WEB-INF\\static\\contract\\" + "contracttemplate.doc";
File file = new File(uploadDirPath);
if (!file.exists()) {
file.createNewFile(); //创建文件
}
FileOutputStream outputStream = new FileOutputStream(file);
int size = 0;
while ((size = bais.read(blobSource)) != -1) {
outputStream.write(blobSource, 0, size);
}
if (outputStream != null) {
outputStream.close();
}
}
}
* 文件下载
*
* @param request
* @param response
* @param id
* @throws Exception
* @throws NumberFormatException
*/
private void downLoadFile(HttpServletRequest request, String id)
throws NumberFormatException, Exception {
Contracttemplate ct = contracttemplateService
.queryContracttemplateById(Integer.parseInt(id));
if (ct != null) {
byte[] blobSource = ct.getBlobSource();
ByteArrayInputStream bais = new ByteArrayInputStream(blobSource);
String uploadDir = request.getSession().getServletContext()
.getRealPath("/")
+ "\\WEB-INF\\static\\contract\\";
File fileDir = new File(uploadDir);
if (!fileDir.exists()) {
fileDir.mkdirs(); //创建目录
}
String uploadDirPath = request.getSession().getServletContext()
.getRealPath("/")
+ "\\WEB-INF\\static\\contract\\" + "contracttemplate.doc";
File file = new File(uploadDirPath);
if (!file.exists()) {
file.createNewFile(); //创建文件
}
FileOutputStream outputStream = new FileOutputStream(file);
int size = 0;
while ((size = bais.read(blobSource)) != -1) {
outputStream.write(blobSource, 0, size);
}
if (outputStream != null) {
outputStream.close();
}
}
}
本文详细阐述了如何使用Java处理文件下载请求,包括从数据库查询文件内容、将内容读取到字节数组并创建文件进行下载的过程。重点介绍了文件路径的获取、文件创建与写入操作。
283

被折叠的 条评论
为什么被折叠?



