一、前台
1.上傳頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><form action="../UploadHandleServlet" enctype="multipart/form-data" method="post">上傳檔案1:<input type="file" name="file1"><input type="submit" value="提交"></form></body></html>
2、下載頁面原理同上
二、上傳
package MainServlet;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.List;import java.util.UUID;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadBase;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.ProgressListener;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import Bean.FlieDao;import Bean.ImgDao;import Bean.TB_Flie;import Bean.TB_Img;/** * Servlet implementation class UploadHandleServlet */@WebServlet(name="UploadHandleServlet",urlPatterns="/UploadHandleServlet")public class UploadHandleServlet extends HttpServlet {private static final long serialVersionUID = 1L; //訊息提示//private String massage=""; /** * @see HttpServlet#HttpServlet() */ public UploadHandleServlet() { super(); // TODO Auto-generated constructor stub }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//得到上傳時產生的臨時檔案儲存目錄String tempPath=this.getServletContext().getRealPath("/WEB-INF/temp");/** * 得到上傳檔案的儲存目錄的兩種方法 * 方法1的目錄產生在tomcat目錄下,一旦tomcat清除項目,此檔案就會消失,不為考慮 *1、String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); *方法2的AttFilePath位webxml裡面配置的路徑名稱,此目錄為固定硬碟目錄,不會因為項目移除而消失,穩定可靠 *2、String savePath = this.getServletContext().getInitParameter("AttFilePath"); *///得到上傳檔案的儲存目錄//String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");//得到上傳檔案的儲存目錄String savePath = this.getServletContext().getInitParameter("AttFilePath");File tmpFile=new File(tempPath);//如果臨時檔案不存在,建立臨時目錄eif(!tmpFile.exists()){ tmpFile.mkdir();} String message = ""; try{ //建立一個DiskFileItemFactory工廠DiskFileItemFactory factory=new DiskFileItemFactory();//設定緩衝區的大小為100KB,如果不指定,那麼緩衝區的大小預設是10KBfactory.setSizeThreshold(1024*100);//設定上傳時產生的臨時檔案的儲存目錄factory.setRepository(tmpFile);//建立一個檔案上傳解析器 ServletFileUpload upload = new ServletFileUpload(factory); //監聽檔案上傳進度 upload.setProgressListener(new ProgressListener(){ public void update(long pBytesRead, long pContentLength, int arg2) { System.out.println("檔案大小為:" + pContentLength + ",當前已處理:" + pBytesRead); } }); //設定上傳單個檔案的大小的最大值,目前是設定為1024*1024位元組,也就是1MB upload.setFileSizeMax(1024*1024); //設定上傳檔案總量的最大值,最大值=同時上傳的多個檔案的大小的最大值的和,目前設定為10MB upload.setSizeMax(1024*1024*10); //4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 List<FileItem> list = upload.parseRequest(request); for(FileItem item : list){ //如果fileitem中封裝的是普通輸入項的資料 if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項的資料的中文亂碼問題 String value = item.getString("UTF-8"); //value = new String(value.getBytes("iso8859-1"),"UTF-8"); System.out.println(name + "=" + value); }else{ //得到上傳的檔案名稱, String filename = item.getName(); System.out.println(filename); if(filename==null || filename.trim().equals("")){ continue; } //解決上傳檔案名稱的中文亂碼 upload.setHeaderEncoding("UTF-8"); //注意:不同的瀏覽器提交的檔案名稱是不一樣的,有些瀏覽器提交上來的檔案名稱是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的檔案名稱,如:1.txt //處理擷取到的上傳檔案的檔案名稱的路徑部分,只保留檔案名稱部分 filename = filename.substring(filename.lastIndexOf("\\")+1); /** * 將上傳的檔案儲存到資料庫 * @author baicai * time上傳時間 * filename檔案名稱 * savePath檔案路徑 * */ Date date=new Date(); DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm"); String time=format.format(date); ImgDao imgDao=new ImgDao(); TB_Img tb_Img=new TB_Img(filename,savePath,time); imgDao.UpImg(tb_Img); //得到上傳檔案的副檔名 String fileExtName = filename.substring(filename.lastIndexOf(".")+1); //如果需要限制上傳的檔案類型,那麼可以通過檔案的副檔名來判斷上傳的檔案類型是否合法 System.out.println("上傳的檔案的副檔名是:"+fileExtName); //擷取item中的上傳檔案的輸入資料流 InputStream in = item.getInputStream(); //得到檔案儲存的名稱 String saveFilename = makeFileName(filename); //得到檔案的儲存目錄 String realSavePath = makePath(saveFilename, savePath); //建立一個檔案輸出資料流 FileOutputStream out = new FileOutputStream(realSavePath + "\\" + saveFilename); //建立一個緩衝區 byte buffer[] = new byte[1024]; //判斷輸入資料流中的資料是否已經讀完的標識 int len = 0; //迴圈將輸入資料流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料 while((len=in.read(buffer))>0){ //使用FileOutputStream輸出資料流將緩衝區的資料寫入到指定的目錄(savePath + "\\" + filename)當中 out.write(buffer, 0, len); } //關閉輸入資料流 in.close(); //關閉輸出資料流 out.close(); //刪除處理檔案上傳時產生的臨時檔案 //item.delete(); response.getWriter().println("<script type='text/javascript'>alert('上傳失敗。')</script>"); } } } catch (FileUploadBase.FileSizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("message", "單個檔案超出最大值。。。"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; }catch (FileUploadBase.SizeLimitExceededException e) { e.printStackTrace(); response.getWriter().println("<script type='text/javascript'>alert('上傳檔案的總的大小超出限制的最大值。。。')</script>"); return; }catch (Exception e) { response.getWriter().println("<script type='text/javascript'>alert('上傳失敗。')</script>"); e.printStackTrace(); }} /** * @Method: makeFileName * @Description: 產生上傳檔案的檔案名稱,檔案名稱以:uuid+"_"+檔案的原始名稱 * @param filename 檔案的原始名稱 * @return uuid+"_"+檔案的原始名稱 */ private String makeFileName(String filename){ //2.jpg //為防止檔案覆蓋的現象發生,要為上傳檔案產生一個唯一的檔案名稱 return UUID.randomUUID().toString() + "_" + filename; } /** * 為防止一個目錄下面出現太多檔案,要使用hash演算法打散儲存 * @Method: makePath * @Description: * * @param filename 檔案名稱,要根據檔案名稱產生儲存目錄 * @param savePath 檔案儲存體路徑 * @return 新的儲存目錄 */ private String makePath(String filename,String savePath){ //用日期得到檔案名稱的 Calendar date=Calendar.getInstance(); SimpleDateFormat format1=new SimpleDateFormat( "yyyy-MM-dd"); String name=format1.format(date.getTime()); String dir = savePath + "\\" + name; //upload\2\3 upload\3\5 File file=new File(dir); //如果目錄不存在 if(!file.exists()){ //建立目錄 file.mkdirs(); } return dir; }/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}
三、下載
package MainServlet;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import java.net.URLEncoder;import java.text.SimpleDateFormat;import java.util.Calendar;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class ImgDown */@WebServlet(urlPatterns="/ImgDown",name="ImgDown")public class ImgDown extends HttpServlet {private static final long serialVersionUID = 1L; /* * @see HttpServlet#HttpServlet() */ public ImgDown() { super(); // TODO Auto-generated constructor stub }protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到要下載的檔案名稱 String fileName = request.getParameter("flieName"); fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8"); //上傳的檔案都是儲存在AttFilePath(D:/Code)目錄下的子目錄當中 String savePath = request.getParameter("fliePath"); //通過檔案名稱找出檔案的所在目錄 String path = findFileSavePathByFileName(fileName,savePath); //得到要下載的檔案 File file = new File(path + "\\" + fileName); //如果檔案不存在 if(!file.exists()){ request.setCharacterEncoding("utf-8"); response.getWriter().println("<script type='text/javascript'>alert('您要下載的資源被刪除啦。')</script>"); } //處理檔案名稱 String realname = fileName.substring(fileName.indexOf("_")+1); //設定回應標頭,控制瀏覽器下載該檔案 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8")); //讀取要下載的檔案,儲存到檔案輸入資料流 FileInputStream in = new FileInputStream(path + "\\" + fileName); //建立輸出資料流 OutputStream out = response.getOutputStream(); //建立緩衝區 byte buffer[] = new byte[1024]; int len = 0; //迴圈將輸入資料流中的內容讀取到緩衝區當中 while((len=in.read(buffer))>0){ //輸出緩衝區的內容到瀏覽器,實現檔案下載 out.write(buffer, 0, len); } //關閉檔案輸入資料流 in.close(); //關閉輸出資料流 out.close(); } /* * @Method: findFileSavePathByFileName * @Description: 通過檔案名稱和儲存上傳檔案根目錄找出要下載的檔案的所在路徑 * @param filename 要下載的檔案名稱 * @param saveRootPath 上傳檔案儲存的根目錄,也就是/WEB-INF/upload目錄 * @return 要下載的檔案的儲存目錄 */ public String findFileSavePathByFileName(String filename,String saveRootPath){ //用日期得到檔案名稱的 Calendar date=Calendar.getInstance(); SimpleDateFormat format1=new SimpleDateFormat( "yyyy-MM-dd"); String name=format1.format(date.getTime()); String dir = saveRootPath + "\\" + name; File file=new File(dir); //如果目錄不存在 if(!file.exists()){ //建立目錄 file.mkdirs(); } return dir; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}資料庫部分
1、實體
package Bean;public class TB_Img {private int id;private String flieName;private String fliePath;private String date;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getFlieName() {return flieName;}public void setFlieName(String flieName) {this.flieName = flieName;}public String getFliePath() {return fliePath;}public void setFliePath(String fliePath) {this.fliePath = fliePath;}public void setDate(String date) {this.date = date;}public String getDat() {return date;}public TB_Img(){}public TB_Img(int id,String flieName,String fliePath,String date){this.id=id;this.flieName=flieName;this.fliePath=fliePath;this.date=date;}public TB_Img(String flieName,String fliePath,String date){this.flieName=flieName;this.fliePath=fliePath;this.date=date;}}
2,資料層
package Bean;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;import SqlDB.SqlDB;public class ImgDao {private Connection conn=SqlDB.getConnection();TB_Img tb_Img=null;List<TB_Img> tb_Imgs=null;/** * 上傳檔案圖片 * */public void UpImg(TB_Img tb_Img) throws SQLException{String sql="insert into Img(flieName,fliePath,date)values(?,?,?)";PreparedStatement ptmt=conn.prepareStatement(sql);ptmt.setString(1, tb_Img.getFlieName());ptmt.setString(2, tb_Img.getFliePath());ptmt.setString(3, tb_Img.getDat());ptmt.executeUpdate();}/** *得到所有資料 * */public List<TB_Img> AllImg() throws SQLException{tb_Imgs=new ArrayList<>();String sql="select * from Img";PreparedStatement ptmt=conn.prepareStatement(sql);ResultSet rs=ptmt.executeQuery();while(rs.next()){tb_Img=new TB_Img();tb_Img.setId(rs.getInt("id"));tb_Img.setFlieName(rs.getString("flieName"));tb_Img.setFliePath(rs.getString("fliePath"));tb_Img.setDate(rs.getString("date"));tb_Imgs.add(tb_Img);}return tb_Imgs;}/** *下載查看檔案 * */public List<TB_Img> FindImg(String context) throws SQLException{tb_Imgs=new ArrayList<>();String sql="select * from Img where flieName like '%"+context +"%' or fliePath like '%"+context +"%' or id like '%"+context +"%'";PreparedStatement ptmt=conn.prepareStatement(sql);ResultSet rs=ptmt.executeQuery();while(rs.next()){tb_Img=new TB_Img();tb_Img.setId(rs.getInt("id"));tb_Img.setFlieName(rs.getString("flieName"));tb_Img.setFliePath(rs.getString("fliePath"));tb_Imgs.add(tb_Img);}return tb_Imgs;}}
3.連結資料庫
package SqlDB;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class SqlDB {private static final String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=Text";private static final String user= "sa";private static final String password="123456"; /** * 擷取串連 * @return */ public static Connection getConnection(){ try { Class.forName(DRIVER); Connection conn = DriverManager.getConnection(URL,user,password); return conn; } catch (SQLException e) { System.out.println(e.getMessage()); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } return null; } /* * 關閉資料庫連接,注意關閉的順序 */ public void close(ResultSet rs, PreparedStatement ps, Connection conn) { if(rs!=null){ try{ rs.close(); rs=null; }catch(SQLException e){ e.printStackTrace(); } } if(ps!=null){ try{ ps.close(); ps=null; }catch(SQLException e){ e.printStackTrace(); } } if(conn!=null){ try{ conn.close(); conn=null; }catch(SQLException e){ e.printStackTrace(); } } } }