2. Use commons upload to develop file upload function
1) . download the jar package and dependent package of Commons upload and add them to the project project
2) . modify the html form, and set the content code type of the form to multipart / form date
3) . write jsp or servlet to handle file upload and other form data
In the webContent directory, create a directory to save the uploaded file
4) . path to save the file on the server
Code implementation:
jsp page:
effect:<%@ 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> <!-- To upload files, you must enctype Change to multipart/form-date --> <form name="regForm" action="upLoadServlet" method="post" enctype="multipart/form-data"> <table width="500" align="center" border="1"> <tr> <td colspan="2">User registration</td> </tr> <tr> <td>Account number</td> <td><input name="userName" type="text"></td> </tr> <tr> <td>Password</td> <td><input name="password" type="password"></td> </tr> <tr> <td>Head portrait</td> <td><input name="userHead" type="file"></td> </tr> <tr> <td><input type="submit"></td> <td><input type="reset"></td> </tr> </table> </form> </body> </html>
upLoadServlet:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub UserInfo userInfo=new UserInfo();//Use temporary variables to save the data uploaded by users //1. Classify and manage the uploaded files //Get the path of Uploads in the file system String basePath=getServletContext().getRealPath("/uploads"); String tempPath=getServletContext().getRealPath("/temp"); Calendar calendar=Calendar.getInstance(Locale.CHINA); String subPath=calendar.get(Calendar.YEAR)+"/"+calendar.get((Calendar.MONTH)+1); System.out.println(basePath+"/"+subPath); File file=new File(basePath+"/"+subPath); if(!file.exists()){ file.mkdirs();//Create multi-level directory, create different file directories according to date changes, classify and save files } File file2=new File(tempPath); if(!file2.exists()){ file.mkdirs();//Create if the directory is not changed } //2. File upload processing //Document item factory class DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(5*1024); //Maximum cache factory.setRepository(new File(tempPath));//Temporary file directory //Set upload parameters ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(5*1024*1024);//Maximum file limit try { List<FileItem>items=upload.parseRequest(request); for(FileItem fileItem:items){ if(fileItem.isFormField()){ //Text field processing String filedName=fileItem.getFieldName(); System.out.println(filedName); String value=fileItem.getString(); String str=new String(value.getBytes(Charset.forName("ISO-8859-1")),"UTF-8"); if("userName".equals(filedName)){ System.out.println("userName=="+str); userInfo.setUserName(str); }else if ("password".equals(filedName)) { System.out.println("password=="+str); userInfo.setPassword(str); } }else { //Document processing //Prevent exceptions when files are not uploaded if(fileItem.getName()!=null&&fileItem.getName().trim().length()>3){ String fileName=fileItem.getName().toLowerCase();//Convert file names to lowercase int beginIndex=fileName.lastIndexOf("."); if(beginIndex!=-1){ System.out.println(beginIndex); String fileType=fileName.substring(beginIndex); System.out.println("fileType"+fileType); //When the server renames, the UUID algorithm is used to generate a random file name, which is used to rename and upload the file String randomFileName=UUID.randomUUID().toString().toLowerCase()+fileType; System.out.println("randomFileName:"+randomFileName); File uploadFile=new File(basePath+"/"+subPath,randomFileName); System.out.println("uploadFile"+uploadFile.getAbsolutePath()); fileItem.write(uploadFile);//Perform upload userInfo.setUserHead("uploads/"+subPath+"/"+randomFileName); System.out.println("Relative path: "+userInfo.getUserHead()); fileItem.delete();//File uploaded successfully, delete temporary file //This example passes the data to the success page for saving request.getSession().setAttribute("userInfo", userInfo); //3. Save or process the uploaded path response.sendRedirect("success.jsp"); } }else { response.sendRedirect("Upload.jsp"); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace();
Effect demonstration:
File read read through EL expression
Head image: < img SRC = "${userinfo. Userhead}" width = "100px" > when setting the picture size, you cannot set the width and height at the same time, otherwise it will be distorted