Jsp + Servlet implements file upload/download list display (2). servlet File Upload

Source: Internet
Author: User

Jsp + Servlet implements file upload/download list display (2). servlet File Upload

Next, I will talk about:
Jsp + Servlet for file upload and download (1) -- File Upload

This chapter displays the list of uploaded files and optimizes the code in Chapter 1.

Let's talk about the code.

Create an attachment table in mysql

DROP TABLE tbl_accessory;  CREATE TABLE tbl_accessory (  id INT AUTO_INCREMENT PRIMARY KEY,  file_name VARCHAR(500),  file_size DOUBLE(10,2),  file_ext_name VARCHAR(100),  file_path VARCHAR(2000) ) ;  SELECT * FROM tbl_accessory;  DELETE FROM tbl_accessory; 

Create attachment entity class

Package entity. upload;/*** attachment object class ** @ author xusucheng * @ create 2017-12-29 **/public class EntityAccessory {private int id; private String fileName; private double fileSize; private String file_ext_name; private String filePath; public int getId () {return id;} public void setId (int id) {this. id = id;} public String getFileName () {return fileName;} public void setFileName (String fileName) {this. fileName = fileName;} public double getFileSize () {return fileSize;} public void setFileSize (double fileSize) {this. fileSize = fileSize;} public String getFile_ext_name () {return file_ext_name;} public void setFile_ext_name (String file_ext_name) {this. file_ext_name = file_ext_name;} public String getFilePath () {return filePath;} public void setFilePath (String filePath) {this. filePath = filePath ;}}

Create a DBUtil tool class

Package util; import java. SQL. *; import java. io. inputStream; import java. util. properties;/*** database tool class ** @ author xusucheng * @ create 2017-11-18 **/public class DBUtil {// variable private static Connection con = null required to define the link; private static PreparedStatement ps = null; private static ResultSet rs = null; // defines the parameter private static String url = ""; private static String username = ""; private stati C String driver = ""; private static String password = ""; // defines the variable private static Properties pp = null required to read the configuration file; private static InputStream FCM = null; /*** load the driver */static {try {// from dbinfo. the properties configuration file reads the configuration information pp = new Properties (); FD = DBUtil. class. getClassLoader (). getResourceAsStream ("db. properties "); pp. load (FCM); url = pp. getProperty ("url"); username = pp. getProperty ("username"); driver = pp. ge TProperty ("driver"); password = pp. getProperty ("password"); // load the driver Class. forName (driver);} catch (Exception e) {System. out. println ("Driver loading failed! "); E. printStackTrace ();} finally {try {FCM. close ();} catch (Exception e) {e. printStackTrace ();} fiis = null; // automatic garbage collection processing}/*** get Connection link * @ return Connection */public static Connection getConnection () {try {// establish connection con = DriverManager. getConnection (url, username, password);} catch (Exception e) {System. out. println ("database connection failed! "); E. printStackTrace ();} return con;}/* public DBUtil (String SQL) {try {ps = getConnection (). prepareStatement (SQL); // prepare the execution statement} catch (Exception e) {e. printStackTrace () ;}} public void close () {try {con. close (); ps. close ();} catch (SQLException e) {e. printStackTrace () ;}} * // *** unified resource close function * @ param rs * @ param ps * @ param con */public static void close (ResultSet rs, statement ps, Connectio N con) {if (rs! = Null) {try {rs. close () ;}catch (Exception e) {e. printStackTrace () ;}} if (ps! = Null) {try {ps. close () ;}catch (Exception e) {e. printStackTrace () ;}} if (con! = Null) {try {con. close () ;}catch (Exception e) {e. printStackTrace ();}}}}

Create an attachment entity DAO class

Package dao. upload; import entity. upload. entityAccessory; import util. DBUtil; import java. math. bigDecimal; import java. SQL. connection; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. SQLException; import java. util. arrayList; import java. util. list;/*** upload the attachment DAO ** @ author xusucheng * @ create 2017-12-29 **/public class AccessoryDao {public static void add (EntityAcces Sory entity) {Connection conn = DBUtil. getConnection (); String SQL = "insert into tbl_accessory (file_name, file_size, file_ext_name, file_path) values (?,?,?,?) "; Try {PreparedStatement ps = conn. prepareStatement (SQL); ps. setString (1, entity. getFileName (); ps. setDouble (2, entity. getFileSize (); ps. setString (3, entity. getFile_ext_name (); ps. setString (4, entity. getFilePath (); ps.exe cute (); // conn. commit (); DBUtil. close (null, ps, conn);} catch (SQLException e) {e. printStackTrace () ;}} public static List <EntityAccessory> list () {Connection conn = DBUt Il. getConnection (); String SQL = "select id, file_name, file_size, file_ext_name, file_path from tbl_accessory"; List <EntityAccessory> accessoryList = new ArrayList <> (); try {PreparedStatement ps = conn. prepareStatement (SQL); ResultSet rs = ps.exe cuteQuery (); while (rs. next () {EntityAccessory entity = new EntityAccessory (); entity. setId (rs. getInt ("id"); entity. setFileName (rs. getString ("file_name ") ); Entity. setFileSize (new BigDecimal (rs. getDouble ("file_size")/1024 ). setScale (2, BigDecimal. ROUND_HALF_UP ). doubleValue (); entity. setFile_ext_name (rs. getString ("file_ext_name"); entity. setFilePath (rs. getString ("file_path"); accessoryList. add (entity);} DBUtil. close (rs, ps, conn);} catch (SQLException e) {e. printStackTrace ();} return accessoryList;} public static void remove (int id) {Conne Ction conn = DBUtil. getConnection (); String SQL = "delete from tbl_accessory where id =? "; Try {PreparedStatement ps = conn. prepareStatement (SQL); ps. setInt (1, id); ps.exe cute (); // conn. commit (); by default, mysql enables autocommit DBUtil. close (null, ps, conn);} catch (SQLException e) {e. printStackTrace ();}}}

Create list. jsp list page

<Html> 

Create a display list Servlet: listUploadedFilesServlet

Package servlet. upload; import dao. upload. accessoryDao; import entity. upload. entityAccessory; 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 java. io. IOException; import java. util. list;/*** return to the List of uploaded files ** @ author xusucheng * @ create 2017-12-29 **/@ WebServlet ("/listUploadedFiles ") public class extends HttpServlet {@ Override protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// obtain the file List <EntityAccessory> accessoryList = AccessoryDao. list (); request. setAttribute ("accessoryList", accessoryList); request. getRequestDispatcher ("pages/upload/list. jsp "). forward (request, response) ;}@ Override protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost (request, response );}}

Added error. jsp to display upload Failure Information

<% @ Page contentType = "text/html; charset = UTF-8 "language =" java "%> <% @ taglib prefix =" c "uri =" http://java.sun.com/jsp/jstl/core "%> 

Optimized the upload controller in Chapter 1.

Package servlet. upload; import dao. upload. accessoryDao; import entity. upload. entityAccessory; 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. fileu Pload. servlet. servletFileUpload; 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 java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. util. calendar; import java. uti L. iterator; import java. util. list; import java. util. UUID;/*** process File Upload ** @ author xusucheng * @ create 2017-12-27 **/@ WebServlet ("/UploadServlet ") public class UploadServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// set the basic path for file upload String savePath = this. getServletContext (). getRealPath ("/WEB-I NF/uploadFiles "); // set the temporary file path String tempPath = this. getServletContext (). getRealPath ("/WEB-INF/tempFiles"); File tempFile = new File (tempPath); if (! TempFile. exists () {tempFile. mkdir () ;}// defines the error message String errorMessage = ""; // creates the file items factory DiskFileItemFactory factory = new DiskFileItemFactory (); // sets the buffer size factory. setSizeThreshold (1024*100); // set the temporary file path factory. setRepository (tempFile); // create a file upload processor ServletFileUpload upload = new ServletFileUpload (factory); // listen to the file upload progress ProgressListener progressListener = new ProgressListener () {public void upda Te (long pBytesRead, long pContentLength, int pItems) {System. out. println ("reading file:" + pItems); if (pContentLength =-1) {System. out. println ("read:" + pBytesRead + "remaining 0");} else {System. out. println ("total file size:" + pContentLength + "read:" + pBytesRead) ;}}; upload. setProgressListener (progressListener); // solves the Chinese garbled upload of the uploaded file name. setHeaderEncoding ("UTF-8"); // determines whether the submitted data is the data of the upload form if (! ServletFileUpload. isMultipartContent (request) {// obtain the data return in the traditional way;} // set the maximum size of a single file to be uploaded. Currently, the value is set to 1024*1024 bytes, that is, 1 MB // upload. setFileSizeMax (1024*1024); // sets the maximum size of the total number of uploaded files. The maximum value is the sum of the maximum size of multiple files uploaded at the same time. Currently, it is set to 10 MB upload. setSizeMax (1024*1024*10); try {// use the ServletFileUpload parser to parse the uploaded data. The parsed result returns a List <FileItem> set, each FileItem corresponds to the input item List <FileItem> items = upload. parseRequest (request); Iterator <FileItem> I Terator = items. iterator (); while (iterator. hasNext () {FileItem item = iterator. next (); // determine whether the file submitted by jsp is if (item. isFormField () {errorMessage = "Submit a file! "; Break;} else {// file name String fileName = item. getName (); if (fileName = null | fileName. trim () = "") {System. out. println ("the file name is blank! ");} // Handle the file name with path problem submitted by different browsers fileName = fileName. substring (fileName. lastIndexOf ("\") + 1); // file size Long fileSize = item. getSize (); // file extension String fileExtension = fileName. substring (fileName. lastIndexOf (". ") + 1); // determine whether the extension is legal if (! ValidExtension (fileExtension) {errorMessage = "the uploaded file is invalid! "; Item. delete (); break;} // get the file input stream InputStream in = item. getInputStream (); // get the name of the saved file String saveFileName = createFileName (fileName); // get the file storage path String realFilePath = createRealFilePath (savePath, saveFileName ); // create a file output stream FileOutputStream out = new FileOutputStream (realFilePath); // create a buffer byte buffer [] = new byte [1024]; int len = 0; while (len = in. read (buffer)> 0) {// write file out. write (buffer, 0, Len);} // close the input stream in. close (); // close the output stream out. close (); // Delete the temporary file item. delete (); <span style = "color: # FF0000;"> // Save the uploaded file information to the EntityAccessory entity = new EntityAccessory (); entity. setFileName (fileName); entity. setFileSize (fileSize); entity. setFile_ext_name (fileExtension); entity. setFilePath (realFilePath); AccessoryDao. add (entity); </span >}} catch (FileUploadBase. fileSizeLimitExceededException e) {e. PrintStackTrace (); errorMessage = "A single file exceeds the maximum !!! ";} Catch (FileUploadBase. SizeLimitExceededException e) {e. printStackTrace (); errorMessage =" the total size of the uploaded file exceeds the maximum value !!! ";} Catch (FileUploadException e) {e. printStackTrace (); errorMessage =" An error occurred while uploading the file !!! ";}Finally {<span style =" color: # FF0000; "> if (! "". Equals (errorMessage) {request. setAttribute ("errorMessage", errorMessage); request. getRequestDispatcher ("pages/upload/error. jsp "). forward (request, response);} else {response. sendRedirect ("listUploadedFiles") ;}</span >}@ Override protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );} private boolean ValidExtension (String fileExtension) {String [] exts = {"jpg", "txt", "doc", "pdf"}; for (int I = 0; I <exts. length; I ++) {if (fileExtension. equals (exts [I]) {return true ;}} return false;} private String createFileName (String fileName) {return UUID. randomUUID (). toString () + "_" + fileName;}/*** generate a real file path based on the basic path and file name, basic path \ year \ month \ fileName ** @ param basePath * @ param fileName * @ return */pr Ivate String createRealFilePath (String basePath, String fileName) {Calendar today = Calendar. getInstance (); String year = String. valueOf (today. get (Calendar. YEAR); String month = String. valueOf (today. get (Calendar. MONTH) + 1); String upPath = basePath + File. separator + year + File. separator + month + File. separator; File uploadFolder = new File (upPath); if (! UploadFolder. exists () {uploadFolder. mkdirs ();} String realFilePath = upPath + fileName; return realFilePath ;}}

Test Results



Next episode notice: delete attachments!

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.