Java上传文件到数据库

     首先在开始本文之前推荐一篇我非常喜欢的博主——孤傲苍狼的一篇相关博文。

          JavaWeb学习总结(五十)——文件上传和下载 

         

         本文主要介绍如何将文件上传到服务器,并以二进制字符流的形式存入数据库。

          初始准备,MySQL数据库,新建表test,添加字段longblob字段。

          1. 页面代码:closedLoopInfo.jsp


<%@ page contentType="text/html; charset=utf-8" language="java"
	import="java.sql.*" errorPage=""%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%
    String path = request.getContextPath();
    // 获得本项目的地址(例如: http://localhost:8080/MyApp/)赋值给basePath变量    
    String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
    // 将 "项目路径basePath" 放入pageContext中,待以后用EL表达式读出。    
    pageContext.setAttribute("basePath", basePath);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<script type="text/javascript" src="<%=basePath%>static/js/jquery.min.js"></script>
<script src="<%=basePath%>static/js/My97DatePicker/WdatePicker.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
<script type="text/javascript">
   function CheckFile(obj) {
		var filname = $(".fil").val();
		var array = new Array('pdf', 'xlsx', 'docx', 'txt', 'pptx', 'jpg',
				'jpeg', 'xls', 'doc'); //可以上传的文件类型
		var fileContentType = obj.value.match(/^(.*)(\.)(.{1,8})$/)[3]; //这个文件类型正则很有用
		var isExists = false;
		for ( var i in array) {
			if (fileContentType.toLowerCase() == array[i].toLowerCase()) {
				isExists = true;
				alert("文件类型正确");
				return true;
			};
		}
		if (isExists == false) {
			obj.value = null;
			alert("上传文件类型需为pdf,xlsx,docx,txt,pptx,jpg,jpeg,xls,doc!");
			return false;
		}
		return false;
	}
</script>
</head>

<body>
	<div class="main" style="background-color:#e4e4e4;">
		<table class="tab">
			<tr style="height:50px;">
				<td></td>
				<td style="text-align:center;vertical-align:middle;"><label
					style="align:center;width:200%;border-style:solid;border-color:#B0B0B0;border-width:thin;">方案附件上传:</label>
				</td>
				<td></td>
				<td>
				  <form id="fieForm" method="post" enctype="multipart/form-data" action="<%=basePath%>uploadQuestionFile.do" >
    	            <div class="bmbut" id="bmbut1">
    	              <input class="fil" name="single" type="file" οnchange="CheckFile(this)"/>
                      <input class="subm" type="submit" value="上传" />
                    </div>
                  </form>
                </td>
				<td></td>
				<td></td>
			</tr>
		</table>
	</div>
</body>
</html>

       

2.附件上传(uploadQuestionFile.do)


// 获取本地第二个磁盘绝对路径,用来存取临时文件
    public String getDisk() {
	String result = "";
	int count = 0;
	for (File f : File.listRoots()) {
	    result = f.getAbsolutePath();
	    count++;
	    if (count == 2)
		break;
	}
	return result;
    }
    
    // 附件上传
    @SuppressWarnings("rawtypes")
    @RequestMapping("uploadQuestionFile.do")
    public String uploadQuestionFile(HttpServletRequest request)
	    throws ServletException, IOException {
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if (isMultipart) {
	    DiskFileItemFactory factory = new DiskFileItemFactory();
	    // factory.setSizeThreshold(1024 * 10);

	    // 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录
	    // factory.setRepository(new File("f:\\test"));  // 临时文件

	    // 用上面的工厂实例化上传组件,
	    ServletFileUpload upload = new ServletFileUpload(factory);

	    // 设置最大上传大小 10M
	    upload.setSizeMax(1024 * 1024 * 5);
	    String name = "";
	    try {
		List items = upload.parseRequest(request); // 得到所有FileItem
		// 上传文件的个数
		Iterator iter = items.iterator();
		
		// 循环处理所有文件
		while (iter.hasNext()) {
		    FileItem item = (FileItem) iter.next();
		    System.out.println("Item:" + item);
		    // 判断是否是表单元素(<input type="text" />单选,多选等)
		    if (!item.isFormField()) {
			// 得到文件的名称
			name = item.getName();
			// 文件长度
			//long size = item.getSize();  // 过滤大小
			if (name == null || "".equals(name.trim())) {
			    // 未选择上传文件
			    continue;
			}
			// 以下为文件名处理,将上传的文件保存在项目所在目录下。
			// 获取文件名字符串的长度
			// int end = name.length();
			// 返回在此字符串中最右边出现的指定子字符串的索引。
			int begin = name.lastIndexOf("\\");

			// int start = name.lastIndexOf(".");
			// 输出上传文件类型,此处可以进行类型的过滤
			//
			// System.out.println(application.getRealPath("/js")+System.getProperty("file.separator")+name.substring(begin
			// + 1));
			// File file = new File("f:\\"+name.substring(begin + 1,
			// end));
			
			File file = new File("");
			file = new File(getDisk()+ name.substring(begin + 1));
			item.write(file);
			System.out.println("1.name:" + name);
			System.out.println("2.file:" + file);
			byte[] buffer = null;
			try {
			    FileInputStream fis = new FileInputStream(file);
			    ByteArrayOutputStream bos = new ByteArrayOutputStream(
				    1024);
			    byte[] b = new byte[1024];
			    int n;
			    while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			    }
			    fis.close();
			    bos.close();
			    buffer = bos.toByteArray();
			} catch (Exception e) {
			    e.printStackTrace();
			}
			FileRequest filerequest = new FileRequest();
			filerequest.setBytes(buffer);
			filerequest.setFileName(name);
			filerequest.setAppName("apiplatform");
			System.out.println("3.赋值前参数filerequest:" + filerequest);
			System.out.println("4.参数filerequestbuffer:" + buffer);
			System.out.println("5.参数BufferSize:" + buffer.length);
			System.out.println("6.参数filerequestFileName:" + name);
			System.out.println("7.已赋值Bytes:"+ filerequest.getBytes());
			System.out.println("8.已赋值FileName:"+ filerequest.getFileName());
			System.out.println("9.已赋值AppName:"+ filerequest.getAppName());
			System.out.println("最终参数filerequest:" + filerequest);
			
			fileBuffer = buffer;
			
			// 是否调用成功
			// 返回的信息,如果成功返回success,如果失败返回错误信息
			// 文件上传成功,会返回一个文件的唯一标识
			// 格式类似于:group1;M00/00/00/CooWNFYJ6kaAWxe_ACrCAeZ2krc847.zip
			// 将这个结果保存到自己的数据库或其他地方,在以后查找文件时用
			if (file.getPath().endsWith(".xlsx")) {
			    System.out.println("文件类型为xlsx");
			} else if (file.getPath().endsWith(".doc")) {
			    System.out.println("文件类型为doc");
			} else if (file.getPath().endsWith(".pdf")) {
                            System.out.println("文件类型为pdf");
			} else if (file.getPath().endsWith(".txt")) {
			    System.out.println("文件类型为txt");
			} else if (file.getPath().endsWith(".pptx")) {
			    System.out.println("文件类型为pptx");
			} else if (file.getPath().endsWith(".docx")) {
			    System.out.println("文件类型为docx");
			} else {
			    request.setAttribute("Error", "文件格式不正确");
			    System.out.println("文件格式不正确");
			}
			file.delete();
		    }
		}

	    } catch (FileUploadException e) {
		e.printStackTrace();
	    } catch (Exception e) {
		// 处理文件写入时的异常
		e.printStackTrace();
	    }
	}
	return "closedLoopInfo";
    }