Traditional jsp+servlet upload file to server and save image address to database

Recently, the traditional Servlet+jsp method is used to realize the function of uploading the user's head image. It is found that it is much more difficult than using the spring boot framework to upload images. In the middle, there are also various problems. Please record them.

Upload your head

First, write a form to upload the avatar

<div class="panel panel-default">
		<div class="panel-heading">Modifying head</div>
		<div class="panel-body">
			<form action="upload" method="post" enctype="multipart/form-data">
			<input type="hidden" name="userID" value=<%=user.get("userID") %>>
				<input type="file" name="testImg" id="headimg" onchange="show(this)"><br>
				<input type="submit" value="Upload your head">
			</form>

			<div id="touxiang">
				<img class="userinfo-head" src="<%=user.get("userHead") %>" alt='Head portrait' width="100" height="100"
					id="showimg">
			</div>
		</div>
	</div>

Form type enctype = "multipart / form data"
In order to preview the image and upload it after selecting the image, we add a paragraph of js

<script type="text/javascript">
		function show(f) {
			var reader = new FileReader();//Create file read object
			var files = f.files[0];//Get the file in the file component
			reader.readAsDataURL(files);//File read and install to base64 type
			reader.onloadend = function(e) {
				//After loading, get the result and assign it to img
				document.getElementById("showimg").src = this.result;
			}
		}
	</script>

Add a servlet to process the uploaded file

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("Method started executing");
		HttpSession session = req.getSession();
		// Verify whether the request meets the requirements (whether the post request / enctype starts with multipart
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		// If the requirement is not met, the processing of the request will be terminated immediately
		if (!isMultipart) {
			return;
		}
		try {
			// FileItem is the encapsulation of every element in the form
			// Create a factory class of FileItem
			FileItemFactory factory = new DiskFileItemFactory();
			// Create a file upload processor (decoration design mode)
			ServletFileUpload upload = new ServletFileUpload(factory);
			// Parsing request
			List<FileItem> items = upload.parseRequest(req);
			System.out.println(items);

			for (FileItem item : items) {
				// Judge document type
				if (item.isFormField()) {
					// Text type
					String filename = item.getFieldName();
					if (filename.equals("userID")) {
						userID = Integer.parseInt(item.getString("UTF-8"));
						System.out.println(userID);
					}
				} else {
					// file type	
					// Get file suffix
					String imgtype = item.getName().substring(item.getName().lastIndexOf("."));
					// Rename files to prevent duplication
					String imgName = UUID.randomUUID() + imgtype;
					System.out.println();
					// Save the uploaded file to the server
					item.write(new File("E:\\eclipse-workspace1\\HPBUS_front\\WebContent\\image", imgName));

					// Avatar path
					userHead = "image/" + imgName;
					System.out.println("Avatar access path:" + userHead);
					// Save path to database
					dao.updateUserHead(userHead, userID);
					System.out.println("Saved successfully!");
					//Update user information in Session
					HashMap<String, String> user = dao.queryByID(userID);
					session.setAttribute("loginuser", user);
					req.getRequestDispatcher("news?op=index").forward(req, resp);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

Problem 1: since the user information is stored in the Session after the user logs in, how to refresh the page's Avatar after the path of the Avatar has been modified and saved to the database is still not updated, so it is necessary to read the modified user information from the database again and put it into the Session.

Question 2: Why did Session information update the refresh page image or not? Because the project is running on tomcat, the change of eclipse directory content will not be automatically synchronized with the actual content in tomcat, so the project content in Tomcat folder needs to be refreshed every time the image is uploaded.
Solution: windows - > Preferences - > General - > workspace - > refresh using native hooks or polling √
Refresh on access √


Select a preview of the avatar and upload it

Refresh the page, and the user's Avatar is successfully modified √

Published 2 original articles, won praise 1 and visited 28
Private letter follow

Keywords: Session Database Tomcat Eclipse

Added by GetPutDelete on Fri, 21 Feb 2020 17:13:09 +0200