Struts upload picture

Struts upload picture

Today, I have finished the image upload and page display of the last blog.

File upload scheme:

  1. Upload to tomcat server
  2. Upload to the specified file directory, add the mapping relationship between the server and the real directory, so as to decouple the relationship between the uploaded file and tomcat file server
  3. Build binary field in database table and store pictures in database

We use the second method to upload the image to the server and save it to the local, and display it on the jsp page.


jsp page

upload.jsp

<%@ 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="${pageContext.request.contextPath}/sy/clz_upload.action" method="post" enctype="multipart/form-data">
	<input type="hidden" name="cid" value="${clz.cid }" />
		<input type="hidden" name="cname" value="${clz.cname }">
		<input type="hidden" name="cteacher" value="${clz.cteacher }">
		<!-- Be careful: name The corresponding value determines the subcontroller. action Naming of properties -->
		<input type="file" name="file" >
		<input type="submit" >
	</form>
</body>
</html>

Before clzList.jsp changed the image to img tag

Configure the struts-sy.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<package name="sy" extends="base" namespace="/sy">
	
		<action name="/demo_*" class="com.chen.web.HelloAction" method="{1}">
			<result name="rs">/rs.jsp</result>
		</action>
		
		<action name="/stack_*" class="com.chen.test.DemoAction" method="{1}">
			<result name="rs">/rs.jsp</result>
		</action>
		
		<action name="/clz_*" class="com.chen.crud.web.ClazzAction" method="{1}">
			<result name="list">/clzList.jsp</result>
			<result name="preSave">/clzEdit.jsp</result>
			<result name="toList" type="redirectAction">/clz_list</result>
			<result name="toUpload" >/upload.jsp</result>
		</action>
		
	</package>
</struts>

ClazzAction.java wrote upload, preupload method to upload pictures, which can be customized.

package com.chen.crud.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.io.FileUtils;

import com.chen.crud.dao.ClazzDao;
import com.chen.crud.entity.clazz;
import com.chen.crud.util.PageBean;
import com.opensymphony.xwork2.ModelDriven;

public class ClazzAction extends BaseAction implements ModelDriven<clazz>{
	private ClazzDao cld = new ClazzDao();
	private clazz clz = new clazz();
	//img/img/imgContentType/imgFileName
	private File file;
	private String fileContentType;
	private String fileFileName;
	
	
	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String list() {
		PageBean pageBean = new PageBean();
		pageBean.setRequest(request);
		try {
			List<clazz> list = this.cld.list(clz, pageBean);
//			this.result = this.cld.list(clz, pageBean);
			request.setAttribute("clzList",list);
			request.setAttribute("pageBean",pageBean);
		} catch (InstantiationException | IllegalAccessException | SQLException e) {
			e.printStackTrace();
		}
		return "list";
	}
	
	/**
	 * The common method of jump to add and modify page
	 * @return
	 */
	public String preSave() {
		if (clz.getCid()!=0) {
			try {
				clazz c = this.cld.list(clz, null).get(0);
				request.setAttribute("clz", c);
			} catch (InstantiationException | IllegalAccessException | SQLException e) {
				e.printStackTrace();
			}
			
		}
		
		return "preSave";
	}
	
	/**
	 * Upload pictures directly
	 * @return
	 */
	public String upload() {
		try {
			/**
			 * Be careful:
			 * There is no E disk under Linux, and there is only one drive letter under Linux, which means that you need to change the code when packaging to the Linux server.
			 * At this time, it is usually solved by configuring the directory string corresponding to targetPath into the resource file and dynamically reading and saving it through the properties class.
			 *When you need to publish the project to a Linux server, you only need targetPath =/zking/t224/img in the xxx.properties file.
			 */
			String targetDir = "C:/Users/17936/Pictures/Camera Roll";
			//Address saved to database
			String severPath="/upload";
		//	FileUtils.copyFile(file, new File(targetDir+"/"+fileFileName));
			copyBufFile(file, new File(targetDir+"/"+fileFileName));//custom
//			Note: database storage is the network request address, not the local image storage address
			clz.setPic(severPath+"/"+fileFileName);
			this.cld.edit(clz);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return "toList";
	}
	
	/**
	 * FileUtils.copyFile And enhanced by buffer
	 * @param source
	 * @param target
	 * @throws Exception
	 */
	public void copyBufFile(File source,File target) throws Exception {
		BufferedInputStream  in = new BufferedInputStream(new FileInputStream(source));
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target));
		byte[] bbuf = new byte[1024];
		int len = 0;
		while((len = in.read(bbuf))!=-1) {
			out.write(bbuf,0,len);
		}
		in.close();
		out.close();
		
	}
	
	/**
	 * Jump to file upload page
	 * @return
	 */
	public String preUpload() {
		try {
			clazz c = this.cld.list(clz, null).get(0);
			request.setAttribute("clz", c);
		} catch (InstantiationException | IllegalAccessException | SQLException e) {
			e.printStackTrace();
		}
		return "toUpload";
	}
	
	
	
	/**
	 * increase
	 * @return
	 */
	public String add() {
			try {
				result = this.cld.add(clz);
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
					| SQLException e) {
				e.printStackTrace();
			}
		return "toList";
	}
	
	/**
	 * modify
	 * @return
	 */
	public String edit() {
		try {
			this.cld.edit(clz);
		} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
				| SQLException e) {
			e.printStackTrace();
		}
		return "toList";
	}
	
	/**
	 * delete
	 * @return
	 */
	public String del() {
		try {
			this.cld.del(clz);
		} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
				| SQLException e) {
			e.printStackTrace();
		}
		return "toList";
	}
	

	@Override
	public clazz getModel() {
		return clz;
	}
	

}

Interceptor

package com.chen.crud.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class OneInterceptor implements Interceptor{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		System.out.println("===============OneInterceptor=================1");
		String invoke = arg0.invoke();
		System.out.println("===============OneInterceptor=================2");
		return invoke;
	}

}

Define two

Redefining struts-sy.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
	<package name="sy" extends="base" namespace="/sy">
	
	<interceptors>
		<interceptor name="one" class="com.chen.crud.interceptor.OneInterceptor"></interceptor>
		<interceptor name="two" class="com.chen.crud.interceptor.TwoInterceptor"></interceptor>
	</interceptors>
		<action name="/demo_*" class="com.chen.web.HelloAction" method="{1}">
			<result name="rs">/rs.jsp</result>
		</action>
		
		<action name="/stack_*" class="com.chen.test.DemoAction" method="{1}">
			<result name="rs">/rs.jsp</result>
		</action>
		
		<action name="/clz_*" class="com.chen.crud.web.ClazzAction" method="{1}">
			<interceptor-ref name="one"></interceptor-ref>
			<interceptor-ref name="two"></interceptor-ref>
			<result name="list">/clzList.jsp</result>
			<result name="preSave">/clzEdit.jsp</result>
			<result name="toList" type="redirectAction">/clz_list</result>
			<result name="toUpload" >/upload.jsp</result>
		</action>
		
	</package>
</struts>

The difference with filter: first through filter and then through interceptor
Then add this line to server.xml of server

<Context path="/T224_struts/upload" docBase="C:/Users/17936/Pictures/Camera Roll"/>

Then run to show this

Keywords: Struts JSP Java xml

Added by zxsalmanxz on Wed, 30 Oct 2019 17:37:21 +0200