The commons-fileupload jar package provided by Apache is indeed very simple to upload files. Recently, I have to use Servlet/JSP to do an image upload function. I have found a lot of information online, most of which are introduced based on the struts framework. Although some of them also introduce the upload of common-fileupload, those examples are relatively old, and some categories are now abandoned.
Through research and study summary, the upload function has been finally completed. Let me share it with you below.
Case scenarios
A library backend management interface needs to provide the function of uploading book pictures and finally display it on the page.
Realize the effect
Enter the book addition page, and the default image is displayed "No breakthrough yet" (both length and width are 200px), and a button is provided to "upload image", as shown in the following image.
Click the "Upload Picture" button and the upload interface pops up through the mode window, as shown in the figure below.
Select the specified image through the "Browse" button, click the "Upload" button to upload. If the upload is successful, a successful prompt will pop up. After the user clicks "OK", closes the pop-up window and automatically displays the new image on the page, as shown in the figure below.
Code implementation
①First create a book add page: bookAdd.jsp
The hidden tag with the page id photo_id is used to store the image path, which is convenient for submission to the background and stored in the database, and the <img> tag with the id of img_id is used to display the images. All pictures are stored under the server for easy reading. Then, a key js, click button to pop up the upload page through the mode window. When the mode window is popped up, a variable win is defined, which is used to obtain the image path value transmitted back by the mode window.
(Note: Due to security issues, pictures cannot be stored at will. If the project is deployed on the server, the pictures can only be viewed under the server. If you must read pictures that are not under the current server, you need to configure the virtual directory of the server)
<html> <head> <title>Add books</title> <script type="text/javascript"> //Open the upload page function openUpload(){ var win = window.showModalDialog("<%=root%>/Admin/bookUpload.jsp","","dialogWidth:300px;dialogHeight:300px;scroll:no;status:no"); if(win != null){ document.getElementById("photo_id").value = win; document.getElementById("img_id").src = "<%=root%>/"+win; } } </script> </head> <body> <h5>Add book</h5><hr/> <p> Book cover: <label> <input type="hidden" id="photo_id" name="photo" value="images/noimg.png"><input type="button" onclick="openUpload()" value="upload image"/><br/> <img id="img_id" src="<%=root%>/images/noimg.png"> </label> </body> </html> ②Create upload image page, bookUpload.jsp
Note that you must define the <base> tag. The data can be returned to the parent form when the current mode window is closed. The <form> tag also needs to set a property enctype="multipart/form-data" so that the submitted files can be obtained by the background. Click the "Upload" button to transmit the files to the background. The remaining highlight is the background upload processing.
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GBK"> <meta http-equiv="pragma" content="no-cache" /> <span style="color: #ff0000;"><base target="_self"></span> <title>Book picture upload</title> </head> <body> <h5>Picture upload</h5><hr/> <p style="color: red">${requestScope.errorMsg}</p> <form id="form1" name="form1" action="<%=root%>/BookServlet?type=bookUpload" method="post" enctype="multipart/form-data"> <div>Note: The maximum image size cannot exceed 3M!</div> <div><input type="file" name="file_upload"/></div> <div><input type="submit" value="upload"/></div> </form> </body> </html> ③Create an ordinary servlet, only some of the key codes are provided below
The red code part is the key code uploaded, and the others are used as embellishments. Complete these three steps and a simple upload will be achieved.
public class BookServlet extends HttpServlet { private String uploadPath = "eShop/upload/"; // directory for uploading files private String tempPath = "eShop/uploadtmp/"; // temporary file directory private String serverPath = null; private int sizeMax = 3;// maximum image upper limit private String[] fileType = new String[]{".jpg",".gif",".bmp",".png",".jpeg",".ico"}; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { serverPath = getServletContext().getRealPath("/").replace("//", "/"); //Execute when Servlet is initialized. If the uploaded file directory does not exist, it will automatically create if(!new File(serverPath+uploadPath).isDirectory()){ new File(serverPath+uploadPath).mkdirs(); } if(!new File(serverPath+tempPath).isDirectory()){ new File(serverPath+tempPath).mkdirs(); } <span style="color: #ff0000;">DiskFileItemFactory factory = new DiskFileItemFactory();</span> factory.setSizeThreshold(5*1024); //Maximum cache factory.setRepository(new File(serverPath+tempPath));//Temporary file directory <span style="color: #ff0000;">ServletFileUpload upload = new ServletFileUpload(factory);</span> upload.setSizeMax(sizeMax*1024*1024);//Maximum upper limit of file String filePath = null; try { <span style="color: #ff0000;">List<FileItem> items = upload.parseRequest(request);</span>//Get all file list for (FileItem item : items) { //Get filename, this file name includes the path <span style="color: #ff0000;">if(!item.isFormField()){</span> //File name String fileName = item.getName().toLowerCase(); if(fileName.endsWith(fileType[0])||fileName.endsWith(fileType[1])||fileName.endsWith(fileType[2])||fileName.endsWith(fileType[3])||fileName.endsWith(fileType[4])||fileName.endsWith(fileType[5])){ String uuid = UUID.randomUUID().toString(); filePath = serverPath+uploadPath+uuid+fileName.substring(fileName.lastIndexOf(".")); <span style="color: #ff0000;">item.write(new File(filePath));</span> PrintWriter pw = response.getWriter(); pw.write("<script>alert('uploaded successfully'); window.returnValue='"+uploadPath+uuid+fileName.substring(fileName.lastIndexOf("."))+"';window.close();</script>"); pw.flush(); pw.close(); }else{ request.setAttribute("errorMsg", "Upload failed, please confirm that the uploaded file exists and is a picture!"); request.getRequestDispatcher("/Admin/bookUpload.jsp").forward(request, response); } } } } catch (Exception e) { e.printStackTrace(); request.setAttribute("errorMsg", "Upload failed, please confirm that the uploaded file size cannot exceed "+sizeMax+"M"); request.getRequestDispatcher("/Admin/bookUpload.jsp").forward(request, response); } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.