天天看點

bboss mvc檔案上傳下載下傳實戰演練

本文以一個實際的demo工程來介紹,如何通過bbossgroups來實作以下功能:

1.通過MVC實作檔案上傳,通過持久層架構将檔案存入資料庫

2.使用持久層架構從資料庫中擷取檔案實作下載下傳功能(blob下載下傳和轉儲為File下載下傳兩種方式)

3.本文涉及架構子產品:mvc,persistent,taglib,aop/ioc

bboss mvc檔案上傳下載下傳實戰演練

   本文展示如何從MultipartHttpServletRequest中擷取上傳的附件,  後續将撰文介紹直接綁定MultipartFile對象或者數組到控制其方法參數或者po對象屬性的案例。

   本文采用derby資料庫。建庫的腳本為:

CREATE TABLE FILETABLE ( FILENAME VARCHAR(100), FILECONTENT BLOB(2147483647),
 FILEID VARCHAR(100), FILESIZE BIGINT )
      

一、實戰

1.下載下傳的最新的bboss eclipse工程

bboss

2.解壓後将eclipse工程bestpractice\bbossupload導入eclipse

3.修改/bbossupload/src/poolman.xml中derby資料庫檔案路徑:

<url>jdbc:derby:D:/d/workspace/bbossgroups-3.6.0/bestpractice/bbossupload/database/cimdb</url>

其中的D:/d/workspace/bbossgroups-3.6.0/bestpractice/bbossupload/database/cimdb需要修改為你的工程所在的實際路徑

4.準備好tomcat 6和jdk 6或以上

5.在tomcat 6的conf\Catalina\localhost下增加upload.xml檔案,内容為(路徑需要調整為實際路徑):

<?xml version='1.0' encoding='utf-8'?>

<Context docBase="D:\workspace\bbossgroups-3.5\bestpractice\bbossupload\WebRoot" path="/upload" debug="0" reloadable="false">

</Context>

使用者可以根據自己的情況設定docBase屬性的值

6.啟動tomcat,輸入以下位址即可通路bboss mvc的附件上傳下載下傳執行個體了:

http://localhost:8080/upload/upload/main.page

效果如下:

bboss mvc檔案上傳下載下傳實戰演練
bboss mvc檔案上傳下載下傳實戰演練

二、代碼賞析

1.在bboss-mvc.xml中增加以下檔案上傳插件配置:

<property name="multipartResolver"   f:encoding="UTF-8"
         class="org.frameworkset.web.multipart.commons.CommonsMultipartResolver">         

在bboss-mvc.xml中增加下載下傳插件配置-FileMessageConvertor

<property name="httpMessageConverters">
     	<list>
     		<property class="org.frameworkset.http.converter.json.MappingJacksonHttpMessageConverter"/>
     		<property class="org.frameworkset.http.converter.StringHttpMessageConverter"/>
     		<property class="org.frameworkset.http.converter.FileMessageConvertor"/>
     	</list>        
     </property>       

2.檔案上傳下載下傳控制器裝配檔案

<?xml version="1.0" encoding='UTF-8'?>
<properties>
	<property name="/upload/*.page"				
		path:main="/upload.jsp"
		path:ok="redirect:main.page"
		class="org.frameworkset.upload.controller.UploadController"
		f:uploadService="attr:uploadService"
		/>		
	<property name="uploadService"
		class="org.frameworkset.upload.service.UploadService" 
		f:uploadDao="attr:uploadDao"/>
	<property name="uploadDao"
		class="org.frameworkset.upload.dao.impl.UpLoadDaoImpl" />
	<!-- 
	如果啟用配置檔案方式,則打開以下注釋,注釋上述uploadDao即可
	 -->
	<!-- 
	<property name="uploadDao"
		class="org.frameworkset.upload.dao.impl.ConfigSQLUploadDaoImpl" 
		f:executor="attr:uploadDao.configexecutor"/>	
	<property name="uploadDao.configexecutor" class="com.frameworkset.common.poolman.ConfigSQLExecutor">
		<construction>
			<property value="org/frameworkset/upload/dao/impl/uploadsql.xml"/>
		</construction>
     </property> 
      -->
</properties>      

3.控制器實作類代碼-UploadController

package org.frameworkset.upload.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.frameworkset.upload.service.FileBean;
import org.frameworkset.upload.service.UploadService;
import org.frameworkset.util.annotations.RequestParam;
import org.frameworkset.util.annotations.ResponseBody;
import org.frameworkset.web.multipart.MultipartFile;
import org.frameworkset.web.multipart.MultipartHttpServletRequest;
import org.frameworkset.web.servlet.ModelMap;

/**
 * CREATE TABLE FILETABLE ( FILENAME VARCHAR(100), FILECONTENT BLOB(2147483647),
 * FILEID VARCHAR(100), FILESIZE BIGINT )
 * 
 * <p>
 * XMLRequestController.java
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * bboss workgroup
 * </p>
 * <p>
 * Copyright (c) 2009
 * </p>
 * 
 * @Date 2011-6-22
 * @author biaoping.yin
 * @version 1.0
 */
public class UploadController
{

	private UploadService	uploadService;

	public String main(ModelMap model) throws Exception
	{

		try
		{
			model.addAttribute("files", uploadService.queryfiles());
			model.addAttribute("clobfiles", uploadService.queryclobfiles());
		}
		catch (Exception e)
		{
			throw e;
		}
		return "path:main";
	}

	/**
	 * @param request
	 * @param model
	 * @param idNum
	 * @param type
	 * @param des
	 * @param byid
	 * @return
	 */
	public String uploadFile(MultipartHttpServletRequest request)
	{
		Iterator<String> fileNames = request.getFileNames();
		// 根據伺服器的檔案儲存位址和原檔案名建立目錄檔案全路徑		
		try
		{
			while (fileNames.hasNext())
			{
				String name = fileNames.next();
				MultipartFile[] files = request.getFiles(name);				 
//				file.transferTo(dest)
				for(MultipartFile file:files)
				{
					String filename = file.getOriginalFilename();
					if (filename != null && filename.trim().length() > 0)
					{
						uploadService.uploadFile(file.getInputStream(), file
								.getSize(), filename);
					}
				}
			}			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return "path:ok";
	}
	
	
	/**
	 * 
	 * @param upload1 參數名稱要和<input type="file" id="upload1" name="upload1" style="width: 200px"/>
	 *        中的name屬性保持一緻,這樣就能夠自動進行綁定和映射
	 * @return
	 */
//	public String uploadFileWithMultipartFile(@RequestParam(name="upload1")  MultipartFile file)
	public String uploadFileWithMultipartFile(MultipartFile upload1)
	{

		
		// 根據伺服器的檔案儲存位址和原檔案名建立目錄檔案全路徑
		
		try
		{
			String filename = upload1.getOriginalFilename();
			if (filename != null && filename.trim().length() > 0)
			{
				uploadService.uploadFile(upload1.getInputStream(), upload1
						.getSize(), filename);

			}			
			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return "path:ok";
	}
	
	public String uploadFileClobWithMultipartFile(MultipartFile upload1)
	{
		try
		{
			uploadService.uploadClobFile(upload1);			
			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return "path:ok";
	}
	
//	public @ResponseBody File uploaddownFileWithMultipartFile( MultipartFile file) throws IllegalStateException, IOException
	/**
	 * 
	 * @param upload1 參數名稱要和<input type="file" id="upload1" name="upload1" style="width: 200px"/>
	 *        中的name屬性保持一緻
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public @ResponseBody File uploaddownFileWithMultipartFile( MultipartFile upload1) throws IllegalStateException, IOException
	{

		File f = new File("d:/" + upload1.getOriginalFilename());
		upload1.transferTo(f);
		return f;
		// 根據伺服器的檔案儲存位址和原檔案名建立目錄檔案全路徑
		
//		try
//		{
//			String filename = file.getOriginalFilename();
//			if (filename != null && filename.trim().length() > 0)
//			{
//				uploadService.uploadFile(file.getInputStream(), file
//						.getSize(), filename);
//
//			}			
//			
//		}
//		catch (Exception ex)
//		{
//			ex.printStackTrace();
//		}
//		return "path:ok";
	}
	
	/**
	 * @param request
	 * @param model
	 * @param idNum
	 * @param type
	 * @param des
	 * @param byid
	 * @return
	 */
	public String uploadFileWithListBean(List<FileBean> files)
	{			
		
		return "path:ok";
	}
	
	/**
	 * 
	 * @param upload1 參數名稱要和<input type="file" id="upload1" name="upload1" style="width: 200px"/>
	 *        中的name屬性保持一緻,否則就需要@RequestParam來建立映射關系
	 * @return
	 */
//	public String uploadFileWithMultipartFiles(@RequestParam(name="upload1")  MultipartFile[] files)
	public String uploadFileWithMultipartFiles(MultipartFile[] upload1)
	{		
		try
		{ 
			
			for(MultipartFile file:upload1)
			{
				String filename = file.getOriginalFilename();
//				file.transferTo(new File("d:/"+ filename));
				
				if (filename != null && filename.trim().length() > 0)
				{
					uploadService.uploadFile(file.getInputStream(), file
							.getSize(), filename);
	
				}
			}			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return "path:ok";
	}
	
	/**
	 * 
	 * @param upload1 參數名稱要和<input type="file" id="upload1" name="upload1" style="width: 200px"/>
	 *        中的name屬性保持一緻,否則就需要@RequestParam來建立映射關系
	 * @return
	 */
//	public @ResponseBody(charset="UTF-8") String uploadFileWithMultipartFilesJson(@RequestParam(name="upload1")  MultipartFile[] upload1)
	public @ResponseBody(charset="UTF-8") String uploadFileWithMultipartFilesJson(MultipartFile[] upload1)
	{		
		try
		{ 

			for(MultipartFile file:upload1)
			{
				String filename = file.getOriginalFilename();
//				file.transferTo(new File("d:/"+ filename));
				
				if (filename != null && filename.trim().length() > 0)
				{
					uploadService.uploadFile(file.getInputStream(), file
							.getSize(), filename);
	
				}
			}			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return "你好";
	}
	
	/**
	 * @param request
	 * @param model
	 * @param idNum
	 * @param type
	 * @param des
	 * @param byid
	 * @return
	 */
	public String uploadFileWithFileBean(FileBean file)
	{	
		try
		{
			
			//對FileBean對象中的附件進行處理。。。。
			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return "path:ok";
	}

	public String deletefiles() throws Exception
	{

		uploadService.deletefiles();
		return "path:ok";
	}

	public String queryfiles() throws Exception
	{

		
		return "path:ok";
	}

	/**
	 * 直接将blob對應的檔案内容以相應的檔案名響應到用戶端,需要提供request和response對象
	 * 這個方法比較特殊,因為derby資料庫的blob字段必須在statement有效範圍内才能使用,是以采用了空行處理器,來進行處理
	 * 查詢資料庫的操作也隻好放在控制器中處理
	 * @param fileid 參數名稱要和request請求中的參數名稱保持一緻,否則就需要@RequestParam來建立映射關系
	 * @param request
	 * @param response
	 * @throws Exception
	 */
//	public void downloadFileFromBlob(
//			@RequestParam(name = "fileid") String fileid,
//			 HttpServletRequest request, HttpServletResponse response)
//			throws Exception
	public void downloadFileFromBlob(
			String fileid,
			 HttpServletRequest request, HttpServletResponse response)
			throws Exception
	{
		uploadService.downloadFileFromBlob(fileid, request, response);

	}
	
	/**
	 * 直接将blob對應的檔案内容以相應的檔案名響應到用戶端,需要提供request和response對象
	 * 這個方法比較特殊,因為derby資料庫的blob字段必須在statement有效範圍内才能使用,是以采用了空行處理器,來進行處理
	 * 查詢資料庫的操作也隻好放在控制器中處理
	 * @param fileid 用來驗證指定@RequestParam注解的參數,但是RequestParam并沒明顯地指定參數的名稱,則将會用方法參數的名稱
	 * 作為參數名稱
	 * @param request
	 * @param response
	 * @throws Exception
	 */
//	public void downloadFileFromClob(
//			@RequestParam(name = "fileid") String fileid,
//			 HttpServletRequest request, HttpServletResponse response)
//			throws Exception
	public void downloadFileFromClob(
			@RequestParam String fileid,
			 HttpServletRequest request, HttpServletResponse response)
			throws Exception
	{

		uploadService.downloadFileFromClob(fileid, request, response);

	}

	/**
	 * 将資料庫中存儲的檔案内容轉儲到應用伺服器檔案目錄中,然後将轉儲的檔案下載下傳,無需提供response和request對象
	 * 
	 * @param fileid
	 * @return
	 * @throws Exception
	 */
	public @ResponseBody File downloadFileFromFile(String fileid)
			throws Exception
	{

		return uploadService.getDownloadFile(fileid);
	}
	public @ResponseBody File downloadFileFromClobFile(String fileid)
	throws Exception
	{
	
		return uploadService.getDownloadClobFile(fileid);
	}
	

	/**
	 * bbossgroups 3.5版本對aop架構的屬性注入功能做了改進,注入的屬性無需再定義get/set方法
	 */
//	public UploadService getUploadService()
//	{
//
//		return uploadService;
//	}
//
//	public void setUploadService(UploadService uploadService)
//	{
//
//		this.uploadService = uploadService;
//	}

}
      

4.業務元件-UploadService

package org.frameworkset.upload.service;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.frameworkset.upload.dao.UpLoadDao;
import org.frameworkset.web.multipart.MultipartFile;


/**
 * <p>UploadService.java</p>
 * <p> Description: </p>
 * <p> bboss workgroup </p>
 * <p> Copyright (c) 2009 </p>
 * 
 * @Date 2011-6-17
 * @author biaoping.yin
 * @version 1.0
 */
public class UploadService
{
	private UpLoadDao uploadDao;
	public UpLoadDao getUploadDao() {
		return uploadDao;
	}
	public void setUploadDao(UpLoadDao uploadDao) {
		this.uploadDao = uploadDao;
	}
	public void deletefiles() throws Exception
	{

		uploadDao.deletefiles();
		
	}
	public List<HashMap> queryfiles() throws Exception
	{

		// TODO Auto-generated method stub
		return uploadDao.queryfiles();
	}
	public void uploadFile(InputStream inputStream, long size, String filename) throws Exception
	{

		uploadDao.uploadFile(inputStream, size, filename);
		
	}
	
	
	
	public void uploadClobFile(MultipartFile file) throws Exception
	{

		uploadDao.uploadClobFile(file);
		
	}
	
	public File getDownloadFile(String fileid) throws Exception
	{
		return uploadDao.getDownloadFile(fileid);
	}
	
	public void downloadFileFromBlob(String fileid,  HttpServletRequest request,
			HttpServletResponse response) throws Exception
	{
		uploadDao.downloadFileFromBlob(fileid, request, response);
	}
	
	public void downloadFileFromClob(String fileid,  HttpServletRequest request,
			HttpServletResponse response) throws Exception
	{
		uploadDao.downloadFileFromClob(fileid, request, response);
	}
	public  List<HashMap> queryclobfiles() throws Exception
	{

		// TODO Auto-generated method stub
		return uploadDao.queryclobfiles();
	}
	public File getDownloadClobFile(String fileid) throws Exception
	{

		return uploadDao.getDownloadClobFile(fileid);
	}
}

      

5.dao元件代碼-

package org.frameworkset.upload.dao.impl;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.frameworkset.upload.dao.UpLoadDao;

import com.frameworkset.common.poolman.Record;
import com.frameworkset.common.poolman.SQLExecutor;
import com.frameworkset.common.poolman.SQLParams;
import com.frameworkset.common.poolman.handle.FieldRowHandler;
import com.frameworkset.common.poolman.handle.NullRowHandler;
import com.frameworkset.util.StringUtil;

public class UpLoadDaoImpl implements UpLoadDao {
	/**
	 * 上傳附件
	 * @param inputStream
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public boolean uploadFile(InputStream inputStream,long size, String filename) throws Exception {
		boolean result = true;
		String sql = "";
		try {
			sql = "INSERT INTO filetable (FILENAME,FILECONTENT,fileid,FILESIZE) VALUES(#[filename],#[FILECONTENT],#[FILEID],#[FILESIZE])";
			SQLParams sqlparams = new SQLParams();
			sqlparams.addSQLParam("filename", filename, SQLParams.STRING);
			sqlparams.addSQLParam("FILECONTENT", inputStream, size,SQLParams.BLOBFILE);
			sqlparams.addSQLParam("FILEID", UUID.randomUUID().toString(),SQLParams.STRING);
			sqlparams.addSQLParam("FILESIZE", size,SQLParams.LONG);
			SQLExecutor.insertBean(sql, sqlparams);			
			
		} catch (Exception ex) {
			ex.printStackTrace();
			result = false;
			throw new Exception("上傳附件關聯臨控指令布控資訊附件失敗:" + ex);
		} finally {
			if(inputStream != null){
				inputStream.close();
			}
		}
		return result;
	}
	
	public File getDownloadFile(String fileid) throws Exception
	{
		try
		{
			return SQLExecutor.queryTField(
											File.class,
											new FieldRowHandler<File>() {

												@Override
												public File handleField(
														Record record)
														throws Exception
												{

													// 定義檔案對象
													File f = new File("d:/",record.getString("filename"));
													// 如果檔案已經存在則直接傳回f
													if (f.exists())
														return f;
													// 将blob中的檔案内容存儲到檔案中
													record.getFile("filecontent",f);
													return f;
												}
											},
											"select * from filetable where fileid=?",
											fileid);
		}
		catch (Exception e)
		{
			throw e;
		}
	}

	@Override
	public void deletefiles() throws Exception
	{

		SQLExecutor.delete("delete from filetable ");			
	}

	@Override
	public List<HashMap> queryfiles() throws Exception
	{

		return SQLExecutor.queryList(HashMap.class, "select FILENAME,fileid,FILESIZE from filetable");
		
	}

	@Override
	public void downloadFileFromBlob(String fileid, final HttpServletRequest request,
			final HttpServletResponse response) throws Exception
	{

		try
		{
			SQLExecutor.queryByNullRowHandler(new NullRowHandler() {
				@Override
				public void handleRow(Record record) throws Exception
				{

					StringUtil.sendFile(request, response, record
							.getString("filename"), record
							.getBlob("filecontent"));
				}
			}, "select * from filetable where fileid=?", fileid);
		}
		catch (Exception e)
		{
			throw e;
		}
		
	}
	
	
	
}
      

6.表單界面代碼-

<h3>MultipartHttpServletRequest方式</h3>
		<form name="tableInfoForm" id="tableInfoForm" enctype="multipart/form-data" method="post" action="<%=request.getContextPath() %>/upload/uploadFile.page"> 
			<input type="hidden" value="0" name="type"/>
			<table width="600" border="0" cellspacing="0" cellpadding="0" class="tox5 bgcolor1">
				<tr>
					<td>
						<table id="upfileList" align="center">
							<tr>
								<td height="30">檔案:<font style="color:#FF0000">*</font></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/></td>								
							</tr>													
						</table>
						<div align=center>
							
							<a href="<%=request.getContextPath() %>/upload/deletefiles.page" >删除</a>
							<input type="submit" class="xbutton1" id="subb" name="subb" value="上 傳"/>
						</div>
					</td>
				</tr>
			</table>
		</form>	
		
		<h3>MultipartFile方式</h3>
		<form name="tableInfoForm1" id="tableInfoForm1" enctype="multipart/form-data" method="post" action="<%=request.getContextPath() %>/upload/uploadFileWithMultipartFile.page"> 
			<input type="hidden" value="0" name="type"/>
			<table width="600" border="0" cellspacing="0" cellpadding="0" class="tox5 bgcolor1">
				<tr>
					<td>
						<table id="upfileList" align="center">
							<tr>
								<td height="30">檔案:<font style="color:#FF0000">*</font></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/></td>								
							</tr>													
						</table>
						<div align=center>
							
							
							<input type="submit" class="xbutton1" id="subb" name="subb" value="上 傳"/>
						</div>
					</td>
				</tr>
			</table>
		</form>	
		
		<h3>MultipartFile[]方式</h3>
		<form name="tableInfoForm2" id="tableInfoForm2" enctype="multipart/form-data" method="post" 
		action="<%=request.getContextPath() %>/upload/uploadFileWithMultipartFiles.page"> 
			<input type="hidden" value="0" name="type"/>
			<table width="600" border="0" cellspacing="0" cellpadding="0" class="tox5 bgcolor1">
				<tr>
					<td>
						<table id="upfileList" align="center">
							<tr>
								<td height="30">檔案:<font style="color:#FF0000">*</font></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/></td>								
							</tr>													
						</table>
						<div align=center>
							
							
							<input type="submit" class="xbutton1" id="subb" name="subb" value="上 傳"/>
						</div>
					</td>
				</tr>
			</table>
		</form>	
		
		<h3>List BeanMultipartFile方式</h3>
		<form name="tableInfoForm21" id="tableInfoForm21" enctype="multipart/form-data" method="post" 
		action="<%=request.getContextPath() %>/upload/uploadFileWithListBean.page"> 
			<input type="hidden" value="0" name="type"/>
			<table width="600" border="0" cellspacing="0" cellpadding="0" class="tox5 bgcolor1">
				<tr>
					<td>
						<table id="upfileList" align="center">
							<tr>
								<td height="30">檔案:<font style="color:#FF0000">*</font></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/> <input type="text" name="upload1des" style="width: 200px"/></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/> <input type="text" name="upload1des" style="width: 200px"/></td>	
															
							</tr>													
						</table>
						<div align=center>
							
							
							<input type="submit" class="xbutton1" id="subb" name="subb" value="上 傳"/>
						</div>
					</td>
				</tr>
			</table>
		</form>	
		
		
		<h3>FileBean方式</h3>
		<form name="tableInfoForm3" id="tableInfoForm3" enctype="multipart/form-data" method="post" action="<%=request.getContextPath() %>/upload/uploadFileWithFileBean.page"> 
			<input type="hidden" value="0" name="type"/>
			<table width="600" border="0" cellspacing="0" cellpadding="0" class="tox5 bgcolor1">
				<tr>
					<td>
						<table id="upfileList" align="center">
							<tr>
								<td height="30">檔案:<font style="color:#FF0000">*</font></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/></td>								
							</tr>													
						</table>
						<div align=center>
							
							
							<input type="submit" class="xbutton1" id="subb" name="subb" value="上 傳"/>
						</div>
					</td>
				</tr>
			</table>
		</form>	
		
			<h3>clob multipartfile</h3>
		<form name="tableInfoForm4" id="tableInfoForm4" enctype="multipart/form-data" method="post" action="<%=request.getContextPath() %>/upload/uploadFileClobWithMultipartFile.page"> 
			<input type="hidden" value="0" name="type"/>
			<table width="600" border="0" cellspacing="0" cellpadding="0" class="tox5 bgcolor1">
				<tr>
					<td>
						<table id="upfileList" align="center">
							<tr>
								<td height="30">檔案:<font style="color:#FF0000">*</font></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/></td>
																
							</tr>													
						</table>
						<div align=center>
							
							
							<input type="submit" class="xbutton1" id="subb" name="subb" value="上 傳"/>
						</div>
					</td>
				</tr>
			</table>
		</form>	
		
			<h3>upload download multipartfile</h3>
		<form name="tableInfoForm4" id="tableInfoForm5" enctype="multipart/form-data" 
		method="post" action="<%=request.getContextPath() %>/upload/uploaddownFileWithMultipartFile.page"> 
			<input type="hidden" value="0" name="type"/>
			<table width="600" border="0" cellspacing="0" cellpadding="0" class="tox5 bgcolor1">
				<tr>
					<td>
						<table id="upfileList" align="center">
							<tr>
								<td height="30">檔案:<font style="color:#FF0000">*</font></td>
								<td><input type="file" id="upload1" name="upload1" style="width: 200px"/></td>
																
							</tr>													
						</table>
						<div align=center>
							
							
							<input type="submit" class="xbutton1" id="subb" name="subb" value="上 傳"/>
						</div>
						
					</td>
				</tr>
			</table>
		</form>	
		<table>
		<tr><td>blob檔案名稱</td><td>檔案下載下傳</td></tr>
		<pg:empty actual="${files}"><tr><td colspan="2">沒有檔案資訊</td></tr></pg:empty>
		<pg:list requestKey="files">
			<tr><td><pg:cell colName="FILENAME"/></td>
			<td><a href="<%=request.getContextPath() %>/upload/downloadFileFromBlob.page?fileid=<pg:cell colName="FILEID"/>">
			blob方式下載下傳</a>
			<a href="<%=request.getContextPath() %>/upload/downloadFileFromFile.page?fileid=<pg:cell colName="FILEID"/>">
			blob轉儲為檔案方式下載下傳</a>
   		</td></tr>
		</pg:list>
		</table>
		
		<table>
		<tr><td>clob檔案名稱</td><td>檔案下載下傳</td></tr>
		<pg:empty actual="${clobfiles}"><tr><td colspan="2">沒有檔案資訊</td></tr></pg:empty>
		<pg:list requestKey="clobfiles">
			<tr><td><pg:cell colName="FILENAME"/></td>
			<td><a href="<%=request.getContextPath() %>/upload/downloadFileFromClob.page?fileid=<pg:cell colName="FILEID"/>">
			clob方式下載下傳</a>
			<a href="<%=request.getContextPath() %>/upload/downloadFileFromClobFile.page?fileid=<pg:cell colName="FILEID"/>">
			clob轉儲為檔案方式下載下傳</a>
		</td></tr>
		</pg:list>
		</table>      

7.将dao切換為采用配置檔案dao-ConfigSQLUploadDaoImpl

/**
 *  Copyright 2008 biaoping.yin
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.  
 */
package org.frameworkset.upload.dao.impl;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.frameworkset.upload.dao.UpLoadDao;

import com.frameworkset.common.poolman.ConfigSQLExecutor;
import com.frameworkset.common.poolman.Record;
import com.frameworkset.common.poolman.SQLParams;
import com.frameworkset.common.poolman.handle.FieldRowHandler;
import com.frameworkset.common.poolman.handle.NullRowHandler;
import com.frameworkset.util.StringUtil;



/**
 * <p>ConfigSQLUploadDaoImpl.java</p>
 * <p> Description: </p>
 * <p> bboss workgroup </p>
 * <p> Copyright (c) 2009 </p>
 * 
 * @Date 2011-6-17
 * @author biaoping.yin
 * @version 1.0
 */
public class ConfigSQLUploadDaoImpl implements UpLoadDao
{
	private ConfigSQLExecutor executor ;
	/**
	 * 上傳附件
	 * @param inputStream
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public boolean uploadFile(InputStream inputStream,long size, String filename) throws Exception {
		boolean result = true;
		
		try {
			
			SQLParams sqlparams = new SQLParams();
			sqlparams.addSQLParam("filename", filename, SQLParams.STRING);
			sqlparams.addSQLParam("FILECONTENT", inputStream, size,SQLParams.BLOBFILE);
			sqlparams.addSQLParam("FILEID", UUID.randomUUID().toString(),SQLParams.STRING);
			sqlparams.addSQLParam("FILESIZE", size,SQLParams.LONG);
			executor.insertBean("uploadFile", sqlparams);			
			
		} catch (Exception ex) {
			ex.printStackTrace();
			result = false;
			throw new Exception("上傳附件關聯臨控指令布控資訊附件失敗:" + ex);
		} finally {
			if(inputStream != null){
				inputStream.close();
			}
		}
		return result;
	}
	
	public File getDownloadFile(String fileid) throws Exception
	{
		try
		{
			return executor.queryTField(
											File.class,
											new FieldRowHandler<File>() {

												@Override
												public File handleField(
														Record record)
														throws Exception
												{

													// 定義檔案對象
													File f = new File(
															"d:/",
															record
																	.getString("filename"));
													// 如果檔案已經存在則直接傳回f
													if (f.exists())
														return f;
													// 将blob中的檔案内容存儲到檔案中
													record
															.getFile(
																		"filecontent",
																		f);
													return f;
												}
											},
											"getDownloadFile",
											fileid);
		}
		catch (Exception e)
		{
			throw e;
		}
	}

	@Override
	public void deletefiles() throws Exception
	{

		executor.delete("deletefiles");			
	}

	@Override
	public List<HashMap> queryfiles() throws Exception
	{

		return executor.queryList(HashMap.class, "queryfiles");
		
	}

	@Override
	public void downloadFileFromBlob(String fileid, final HttpServletRequest request,
			final HttpServletResponse response) throws Exception
	{

		try
		{
			executor.queryByNullRowHandler(new NullRowHandler() {
				@Override
				public void handleRow(Record record) throws Exception
				{

					StringUtil.sendFile(request, response, record
							.getString("filename"), record
							.getBlob("filecontent"));
				}
			}, "downloadFileFromBlob", fileid);
		}
		catch (Exception e)
		{
			throw e;
		}
		
	}

	
	public ConfigSQLExecutor getExecutor()
	{
	
		return executor;
	}

	
	public void setExecutor(ConfigSQLExecutor executor)
	{
	
		this.executor = executor;
	}

}
      

sql配置檔案内容-

<?xml version="1.0" encoding='gb2312'?>
<properties>
	<property name="deletefiles"><![CDATA[delete from filetable]]>
	</property>
	<property name="queryfiles"><![CDATA[select FILENAME,fileid,FILESIZE from filetable]]>
	</property>
	<property name="uploadFile"><![CDATA[
		INSERT INTO filetable (FILENAME,FILECONTENT,fileid,FILESIZE) 
		VALUES(#[filename],#[FILECONTENT],#[FILEID],#[FILESIZE])]]>
	</property>
	
	<property name="getDownloadFile"><![CDATA[
		select * from filetable where fileid=?
	]]></property>
	
	
</properties>      

代碼都很簡單,也非常容易了解,這裡不做過多的解釋。有問題可以留言讨論,也可以加入群組:

21220580

3625720

154752521

官方網站:

http://www.bbossgroups.com/