文件上传

package com.fileupload;

import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;

import sun.rmi.server.Dispatcher;

public class FileUpLoad extends HttpServlet {
	String result="花木成畦手自栽";
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	/*
	 * 将文件上传到服务器中并保存在硬盘中start public void doPost(HttpServletRequest request,
	 * HttpServletResponse response) throws ServletException, IOException {
	 * 
	 * response.setContentType("text/html;charset=uft-8");
	 * request.setCharacterEncoding("utf-8");
	 * response.setCharacterEncoding("utf-8"); PrintWriter out =
	 * response.getWriter();
	 * 
	 * //设置上传文件的保存目录 , String
	 * uploadDir=getServletContext().getRealPath("/uploadfile");
	 * if(uploadDir==null){ out.println("无法访问存储目录!"); return; } // File
	 * fileupload=new File(uploadDir); if(!fileupload.exists()){
	 * //不存在则在当前应用下创建这个文件夹 if(!fileupload.mkdir()){ out.print("无法创建该目录!");
	 * return; } } DiskFileUpload dsfileup=new DiskFileUpload();
	 * //设置上传的普通字段的名称和文件字段的文件名所采用的字符集编码
	 * dsfileup.setHeaderEncoding(request.getCharacterEncoding()); //设置上传文件的最大值
	 * dsfileup.setSizeMax(1024*1024*200);
	 * 
	 * //得到所有表单字段对象的集合 List fileItems=null; try {
	 * fileItems=dsfileup.parseRequest(request); } catch (FileUploadException e) { //
	 * TODO Auto-generated catch block out.print("解析数据时出现以下异常!");
	 * e.printStackTrace(out); } //处理每个表单的数据 Iterator item=fileItems.iterator();
	 * while(item.hasNext()){ FileItem fi=(FileItem)item.next();
	 * if(fi.isFormField()){ out.print("表单名:"+fi.getFieldName()+"<br>表单值:"+fi.getString("utf-8")+"<br>");
	 * }else{ if(fi.getFieldName()!=null&&!fi.getName().equals("")){ out.print("<br>上传文件的大小为:"+fi.getSize()+"KB");
	 * out.print("<br>上传文件的类型为:"+fi.getContentType()); out.print("<br>上传文件的名称为:"+fi.getName());
	 * File tempfile=new File(fi.getName()); File file=new
	 * File(uploadDir,tempfile.getName()); try { fi.write(file); out.print("<br>上传文件成功!<br>"); }
	 * catch (Exception e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); out.print("<br>上传文件失败"); }
	 * 
	 * }else{ out.print("<br>请选择上传文件!"); } } } } 将文件上传到服务器中并保存在硬盘中stop
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		DiskFileUpload upload = new DiskFileUpload();
		// 设置转换时的编码
		upload.setHeaderEncoding(request.getAuthType());
		// 设置上传文件的最大值为100M
		upload.setSizeMax(1024 * 1024 * 100);
		// 设置上专文件时使用临时文件的临届值
		upload.setSizeThreshold(1024 * 1024 * 20);
		List fileItems = null;
		// 如果是多媒体格式则用List集合保存所有的字段元素值
		if (upload.isMultipartContent(request)) {
			try {
				fileItems = upload.parseRequest(request);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 迭代List集合,并将所有表单元素的值与名字放入到Map集合中
		HashMap map = new HashMap();
		Iterator item = fileItems.iterator();
		// 循环得到FileItem对象
		while (item.hasNext()) {
			FileItem fi = (FileItem) item.next();
			// 如果是普通表单,将表单名与值放入到map集合中
			if (fi.isFormField()) {
				map.put(fi.getName(), fi.getString());
			} else {
				// 如果是多媒体数据,则将对象名与对象放到map集合中
				map.put(fi.getFieldName(), fi);
			}
		}
		// 并将文件写入到数据 库中
		save((FileItem) map.get("fileUpLoad"));
		// System.out.print("对象是"+(FileItem)map.get("fileUpLoad"));
		//将上传的结果放到request对象中。
		request.setAttribute(result,result);
		//构建临时文件。用来取得上传文件的文件名。
		File tempfile = new File(((FileItem)map.get("fileUpLoad")).getName());
		//转交到显存图片的servlet进行处理
		RequestDispatcher rd=request.getRequestDispatcher("showImage.jsp?filename="+tempfile.getName());
		rd.forward(request, response);
	}

	public void save(FileItem fileitem) {
		// 创建一个临时文件。用来得到上传文件中不带路径的文件名
		File tempfile = new File(fileitem.getName());
		// String filename=tempfile.getName();
		// System.out.print(filename);
		Connection con = null;
		try {
			// 调用DBHelper类的getgetInstance方法得到一个类的实例。并调用实例方法getConnection得到一个连接
			con = DBHelper.getgetInstance().getConnection();
			String sql = "insert into bookImage ([filename],image)values(?,?) ";
			// 创建一个PreparedStatement对象预编译SQL语句
			PreparedStatement ps = con.prepareStatement(sql);

			// 把FileItem对象的主体内容转换成输入流
			InputStream is = fileitem.getInputStream();
			// 为SQL语句传参数值
			ps.setString(1, tempfile.getName());
			ps.setBinaryStream(2, is, (int) fileitem.getSize());
			// 执行编译好的SQL语句
			int num = ps.executeUpdate();
			if (1 != num){
				System.err.println("上傳失敗");
				result="上傳失敗";
			}else{
			ps.close();
			is.close();
			System.out.println("上傳成功");
			result="上傳成功";
			}
		} catch (Exception e) {
			System.out.print(e.getMessage());
		}finally{
			try {
				// close the connection
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

 

你可能感兴趣的:(sql,应用服务器,jsp,SQL Server,servlet)