Struts2文件上传

Java Web 专栏收录该内容
23 篇文章 0 订阅

Struts2文件上传

目录:

1、Tomcat报错处理:

2、文件上传jar包引入:

3、form表单配置:

4、Action添加属性:

5、其它:

6、源代码示例:

7、配置文件:

8、页面源码:

9、运行结果:

10、文件类型和后缀名:


1、Tomcat报错处理:

(1)Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/tx]

Offending resource: class path resource [application.xml]

答:没有导入jar包,加上

<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-tx</artifactId>

<version>4.2.5.RELEASE</version>

</dependency>

(2)Invalid bean definition with name 'dataSource' defined in class path resource [application.xml]: Could not resolve placeholder 'jdbc.driverClassName' in string value "${jdbc.driverClassName}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'jdbc.driverClassName' in string value "${jdbc.driverClassName}"

答:在spring的配置文件中,

<!-- 引入配置文件 -->

<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true" />

此行加上 ignore-unresolvable="true"

(3)nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.remoa.dao.Userdao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

答:在dao层的实现类加上@Repository

(4)Unable to find 'struts.multipart.saveDir' property setting.

答:struts.multipart.saveDir没有配置,用于存放指定临时文件的文件夹,在struts.xml加上:

<constant name="struts.multipart.saveDir" value="/tmp"/>

(5)Can not issue data manipulation statements with executeQuery().

答:可能是当要insert时,使用了ps.executeQuery()用错,改为ps.executeUpdate()方法。

(6)Data truncation: Data too long for column 'password' at row 1

答:因为用了MD5Util加密,所以数据库里的password字段定义为vatchar(20)太短了,博主修改为varchar(100)可使用。

(7)Servlet.service() for servlet jsp threw exception

javax.el.PropertyNotFoundException: Property 'account' not found on type java.lang.String

答:jsp页面的el表达式错了,看看是不是粗心没加$

(8)严重: Servlet.service() for servlet jsp threw exception

org.apache.jasper.JasperException

答:单双引号的混乱,根据报错的提示行数看JSP页面

 

2、文件上传jar包引入:

答:commons-fileupload-1.3.2.jar

commons-io-2.4.jar

 

3、form表单配置:

答:凡是要用commons-fileupload上传文件的表单都必须设置enctype属性,且属性的值必须是multipart/form-data,同时请求方法必须是post

enctype="multipart/form-data"

 

4、Action添加属性:

答:private File xxx;

private String xxxFileName;

private String xxxContentType;

然后加上getter和setter方法

 

5、其它:

答:限制上传文件的大小和文件类型

//默认限制2M,5242880字节/ 1024 / 1024 = 5

<constant name="struts.multipart.maxSize" value="5242880"/>

 

@InterceptorRef(value="defaultStack",

params={"fileUpload.maximumSize","5242880",

"fileUpload.allowedTypes","image/jpeg,image/png",

"fileUpload.allowedExtensions",".jpg,.jpeg,.jpe,.png"})

说明:

先判断fileUpload.maximumSize条件,如果通过再判断struts.multipart.maxSize条件

 

6、源代码示例:

(1)说明:

本源代码在eclipse集成开发环境下模拟,使用maven管理工具,jdk版本为1.8,Tomcat版本为8.0,数据库管理系统使用MySQL,演示Struts2框架下的文件上传,其中action交付给Spring进行管理,模拟了一个注册表单的提交,包括账户名,密码,性别,及头像上传,其中密码使用了MD5Util加密方式,然后在show.jsp页面对数据库中存放的所有用户信息进行展示。

(2) 包目录结构:


图6.1 包目录结构1


图6.2 包目录结构2

(3)代码示例:

①AddUserAction.java

package com.remoa.action;

import java.io.File;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.remoa.domain.User;
import com.remoa.service.UserService;

@Namespace("/user")
@Results({@Result(name="show", location="show.jsp"),
	@Result(name="upload", location="upload.jsp")
})
@InterceptorRef(value="defaultStack",
params={"fileUpload.maximumSize","5242880",
		"fileUpload.allowedTypes","image/jpeg,image/png",//允许的文件类型
		"fileUpload.allowedExtensions",".jpg,.jpeg,.jpe,.png"})
public class AddUserAction extends ActionSupport implements ModelDriven<User>{
	private static final long serialVersionUID = 1L;
	@Autowired
	private UserService service;
	private List<User> userList;
	private User user = new User();
	private File myFile;
	private String myFileFileName;
	private String myFileContentType;
	
	public UserService getService() {
		return service;
	}

	public void setService(UserService service) {
		this.service = service;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public File getMyFile() {
		return myFile;
	}

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	public String getMyFileFileName() {
		return myFileFileName;
	}

	public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}

	public String getMyFileContentType() {
		return myFileContentType;
	}

	public void setMyFileContentType(String myFileContentType) {
		this.myFileContentType = myFileContentType;
	}

	@Action("doUpload")
	public String doUpload() throws Throwable{
		System.out.println(this.myFile.getAbsolutePath());
		System.out.println(this.myFileFileName);
		System.out.println(this.myFileContentType);
		String fileName = UUID.randomUUID().toString() + this.myFileFileName.substring(this.myFileFileName.lastIndexOf('.'));
		user.setHeadImg(fileName);
		service.register(user);
		FileUtils.copyFile(this.myFile, new File("d:/apps/" + fileName));
		return "upload";
	}
	
	@Action("upload")
	public String upload() throws Throwable{
		return "upload";
	}
	
	@Action("show")
	public String show()throws Throwable{
		userList = service.listUser();
		System.out.println(userList);
		ActionContext.getContext().put("userList", userList);
		return "show";
	}
	
	@Override
	public User getModel() {
		return this.user;
	}
}
②ConnectionFactory.java

package com.remoa.common;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

public class ConnectionFactory {
	private static ThreadLocal<Connection> thlocal = new ThreadLocal<Connection>();
	private BasicDataSource dataSource;
	private static ConnectionFactory instance = new ConnectionFactory();
	public static ConnectionFactory getInstance() {
		return instance;
	}
	private ConnectionFactory(){
		Properties pro = new Properties();
		try {
			InputStream input = this.getClass().getResourceAsStream("/jdbc.properties");
			pro.load(input);
			input.close();
			dataSource = (BasicDataSource)BasicDataSourceFactory.createDataSource(pro);
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	
	public Connection getConnection() throws SQLException{
		return dataSource.getConnection();
	}
	
	public static Connection getLocalThreadConnection() throws SQLException{
		Connection conn = thlocal.get();
		if(conn == null){
			Connection localConn = instance.getConnection();
			thlocal.set(localConn);
			return conn;
		}else{
			return conn;
		}
	}
	
	public static void closeAll(Connection conn, Statement st, ResultSet rs){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(st != null){
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args){
		System.out.println(ConnectionFactory.getInstance().getClass().getName());
	}
}
③InitListener.java
package com.remoa.common;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class InitListener implements ServletContextListener{

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		sce.getServletContext().setAttribute("path", sce.getServletContext().getContextPath());
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}
}
④Userdao.java

package com.remoa.common;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class InitListener implements ServletContextListener{

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		sce.getServletContext().setAttribute("path", sce.getServletContext().getContextPath());
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {

	}
}
⑤UserdaoImp.java

package com.remoa.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.remoa.common.ConnectionFactory;
import com.remoa.domain.User;

@Repository
public class UserdaoImp implements Userdao{
	private String addSql = "insert into user(account, password, sex, headImg) values(?,?,?,?)";
	@Override
	public void add(User user) throws Throwable {
		Connection conn = ConnectionFactory.getInstance().getConnection();
		PreparedStatement ps = conn.prepareStatement(addSql);
		ps.setString(1, user.getAccount());
		ps.setString(2, user.getPassword());
		ps.setString(3, user.getSex());
		ps.setString(4, user.getHeadImg());
		ps.executeUpdate();
		ConnectionFactory.closeAll(conn, ps, null);
	}

	@Override
	public void delete(int id) throws Throwable {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void update(User user) throws Throwable {
		// TODO Auto-generated method stub
		
	}

	@Override
	public User getUserById(int id) throws Throwable {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public User getUserByAccount(String account) throws Throwable {
		// TODO Auto-generated method stub
		return null;
	}

	private String listSql = "select * from user";
	@Override
	public List<User> list() throws Throwable {
		Connection conn = ConnectionFactory.getInstance().getConnection();
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery(listSql);
		List<User> list = new ArrayList<User>();
		while(rs.next()){
			User user = new User();
			user.setId(rs.getInt(1));
			user.setAccount(rs.getString(2));
			user.setPassword(rs.getString(3));
			user.setSex(rs.getString(4));
			user.setHeadImg(rs.getString(5));
			list.add(user);
		}
		System.out.println(list);
		System.out.println("-------------");
		return list;
	}
}
⑥User.java

package com.remoa.domain;

public class User {
	private int id;
	private String account;
	private String password;
	private String sex;
	private String headImg;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getHeadImg() {
		return headImg;
	}
	public void setHeadImg(String headImg) {
		this.headImg = headImg;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", account=" + account + ", password=" + password + ", sex=" + sex + ", headImg="
				+ headImg + "]";
	}
}
⑦UserService.java

package com.remoa.service;

import java.util.List;

import com.remoa.domain.User;

public interface UserService {
	/**
	 * 用户注册
	 * @param user
	 * @throws Throwable
	 */
	public void register(User user)throws Throwable;
	/**
	 * 展示用户列表 
	 * @return
	 * @throws Throwable
	 */
	public List<User> listUser() throws Throwable;
}
⑧UserServiceImp.java

package com.remoa.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.remoa.dao.Userdao;
import com.remoa.domain.User;
import com.remoa.util.MD5Util;

@Service
public class UserServiceImp implements UserService{
	@Autowired
	private Userdao dao;
	@Override
	public void register(User user) throws Throwable {
		user.setPassword(MD5Util.md5(user.getPassword()));
		dao.add(user);
	}
	@Override 
	public List<User> listUser() throws Throwable{
		List<User> userList = dao.list();
		return userList;
	}
}
⑨MD5Util.java

package com.remoa.util;

import java.security.MessageDigest;

public class MD5Util {
	public static String md5(String source) throws Exception{  
        String des = "";  
        MessageDigest md = MessageDigest.getInstance("MD5");  
        byte[] result = md.digest(source.getBytes());  
        StringBuilder buf = new StringBuilder();  
        for (int i=0;i<result.length;i++) {  
            byte b = result[i];  
            buf.append(String.format("%02X", b));  
        }  
        des = buf.toString().toLowerCase();  
        return des;  
    }   
}
⑩SpringUtil.java

package com.remoa.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringUtil{
	
	private static ApplicationContext ctx;
	public static void init(String path){
		ctx=new ClassPathXmlApplicationContext(path);
	}
	
	public static Object getBean(String id){
		return ctx.getBean(id);
	}
	
	public static <T> T getBean(Class<T> type){
		
		return ctx.getBean(type);
	}
	
}

7、配置文件:
(1)pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.remoa</groupId>
	<artifactId>struts2Learn</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<build>
		<finalName>struts</finalName>
		<!-- 默认源代码和资源文件目录配置 -->
		<sourceDirectory>src/main/java </sourceDirectory>
		<testSourceDirectory>src/test/java</testSourceDirectory>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
		</resources>
		<testResources>
			<testResource>
				<directory>src/test/resources</directory>
			</testResource>
		</testResources>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-spring-plugin</artifactId>
			<version>2.5.2</version>
		</dependency>
		<!-- struts2注解零配置依赖的包 -->
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-convention-plugin</artifactId>
			<version>2.5.2</version>
		</dependency>
		<!-- Servlet规范包 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<!-- 众多接口的集合,它不负责日志的具体实现,只在编译时负责寻找合适的日志系统进行绑定 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.2</version>
		</dependency>
		<!-- 具体的日志系统,通过slf4j-log4j12初始化log4j,达到最终日志的输出 -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.5</version>
		</dependency>
		<!-- 文件上传组件 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.2</version>
		</dependency>
		<!-- 文件上传组件 -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<!-- jsp标签库 -->
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>jstl</artifactId>
		    <version>1.2</version>
		</dependency>
		<!-- 使用dbcp连接池 -->
		<dependency>
		    <groupId>commons-dbcp</groupId>
		    <artifactId>commons-dbcp</artifactId>
		    <version>1.4</version>
		</dependency>
		<!-- MySQL驱动 -->
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>5.1.38</version>
		</dependency>
	</dependencies>
</project>
(2)application.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-4.2.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
	<!-- 只扫描service -->
	<context:component-scan base-package="com.remoa">
	
	</context:component-scan>
	<!-- 引入配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true" />
	<!--创建数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<!--maxActive: 最大连接数量 -->
		<property name="maxActive" value="5" />
		<!--minIdle: 最小空闲连接 -->
		<property name="minIdle" value="2" />
		<!--maxIdle: 最大空闲连接 -->
		<property name="maxIdle" value="10" />
		<!--initialSize: 初始化连接 -->
		<property name="initialSize" value="5" />
		<!-- 连接被泄露时是否打印 -->
		<property name="logAbandoned" value="true" />
		<!--removeAbandoned: 是否自动回收超时连接 -->
		<property name="removeAbandoned" value="true" />
		<!--removeAbandonedTimeout: 超时时间(以秒数为单位) -->
		<property name="removeAbandonedTimeout" value="30" />
		<!--maxWait: 超时等待时间以毫秒为单位 -->
		<property name="maxWait" value="60000" />
		<!-- 在空闲连接回收器线程运行期间休眠的时间值,以毫秒为单位. -->
		<property name="timeBetweenEvictionRunsMillis" value="10000" />
		<!-- 在每次空闲连接回收器线程(如果有)运行时检查的连接数量 -->
		<property name="numTestsPerEvictionRun" value="10" />
		<!-- 1000 * 60 * 30 连接在池中保持空闲而不被空闲连接回收器线程 -->
		<property name="minEvictableIdleTimeMillis" value="10000" />
		<property name="validationQuery" value="${jdbc.validationQuery}" />
	</bean>
	
</beans>
(3)jdbc.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/strutsLearn?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=123456
initialSize=5
maxTotal=10
maxIdle=10
minIdle=2
validationQuery=select 1
(4)log4j.properties

log4j.rootLogger=INFO,console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd  HH:mm:ss,SSS}  [%c]-[%p]%m%n
  
log4j.logger.java.sql=DEBUG   
(5)log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="org.apache.struts2" level="info"/>
        <Root level="info">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>
</Configuration>
(6)struts.xml

<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">  
<struts>
	<include file="struts-default.xml"></include>
	<!-- 指定被struts2处理的请求后缀类型。多个用逗号隔开 -->  
    <constant name="struts.action.extension" value="action"/>  
     <!-- 是否开启动态方法调用 -->  
	<constant name="struts.enable.DynamicMethodInvocation" value="true" /> 
	<!-- 是否使用struts的开发模式。开发模式会有更多的调试信息。默认值为false(生产环境下使用),开发阶段最好打开  -->  
    <constant name="struts.devMode" value="true"/>
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <constant name="struts.convention.result.path" value="/WEB-INF/pages"/>
     <!-- 进行扫描的根包,该包会被扫描成action -->
    <constant name="struts.convention.package.locators" value="action"/>
     <!-- 设置浏览器是否缓存静态内容。默认值为true(生产环境下使用),开发阶段最好关闭  -->  
    <constant name="struts.serve.static.browserCache" value="false" />  
     <!-- 指定由spring负责action对象的创建 -->
    <constant name="struts.objectFactory" value="spring"/>
    <!-- 当struts.xml改动后,是否重新加载。默认值为false(生产环境下使用),开发阶段最好打开  -->  
    <constant name="struts.configuration.xml.reload" value="true"/>
	<constant name="struts.multipart.maxSize" value="5242880"/>
	<constant name="struts.multipart.saveDir" value="/tmp"/>
	
</struts>

8、页面源码:
(1)show.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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">
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<script type="text/javascript" src="${path }/bootstrap/js/jquery.min.js" ></script>
	<script type="text/javascript" src="${path }/bootstrap/js/bootstrap.min.js" ></script>
	<link rel="stylesheet" href="${path }/bootstrap/css/bootstrap.min.css" />
	<title>展示</title>
</head>
<body>
	<div class="col-md-6">
		<c:forEach items="${userList }" var="item">
			账户名:${item.account }<br/>
			密码:${item.password }<br/>
			性别:${item.sex }<br/>
			<img src="/images/${item.headImg }" class="img img-circle" width="100px" height="100px"/><br/>
		</c:forEach>
	</div>
</body>
</html>
(2)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">
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<script type="text/javascript" src="${path }/bootstrap/js/jquery.min.js" ></script>
	<script type="text/javascript" src="${path }/bootstrap/js/bootstrap.min.js" ></script>
	<link rel="stylesheet" href="${path }/bootstrap/css/bootstrap.min.css" />
	<title>文件上传</title>
</head>
<body>
	<div class="col-md-7" style="text-align:center">
		文件上传学习:
	</div>
	<div class="col-md-6">
		<form class="form" action="doUpload.action" method="post" enctype="multipart/form-data" role="form" >
			<div class="form-group col-md-12">
				<label for="account" class="col-md-3 control-label">
					账户:
				</label>
				<div class="col-md-9 col-md-12">
					<input type="text" name="account" class="form-control" placeholder="请输入账户名" />
				</div>
			</div>
			<div class="form-group col-md-12">
				<label for="password" class="col-md-3 control-label">
					密码:
				</label>
				<div class="col-md-9">
					<input type="password" name="password" class="form-control" placeholder="请输入密码" />
				</div>
			</div>
			<div class="form-group col-md-12">
				<label for="sex" class="col-md-3 control-label">  
               		性别:  
                </label>  
                <div class="col-md-9">  
                    <label class="radio-inline">  
                        <input type="radio" name="sex" value="male" checked />男  
                    </label>  
                    <label class="radio-inline">  
                        <input type="radio" name="sex" value="female" />女  
                    </label>  
                </div>  
			</div>
			<div class="form-group col-md-12">
				<label for="file" class="col-md-3 control-label">
					头像上传:
				</label>
				<div class="col-md-3">
					<input type="file" name="myFile" />
				</div>
				<div class="col-md-6"></div>
			</div>
			<input type="submit" class="btn btn-success col-md-offset-3" value="提交" />
			<input type="reset" class="btn btn-primary col-md-offset-1" value="重置" />
		</form>
		<a href="${path }/user/show.action">查看所有用户</a>
	</div>
</body>
</html>

9、运行结果:

答:(1)页面展示结果:


图9.1 页面运行结果1


图9.2 页面运行结果2

(2)数据库表结果:


图9.3 数据库表结果

(3)本地目录下图片上传结果:


图9.4 本地存放头像图片目录查看

 

10、文件类型和后缀名:

'.a': 'application/octet-stream'   

'.ai': 'application/postscript'   

'.aif': 'audio/x-aiff'   

'.aifc': 'audio/x-aiff'   

'.aiff': 'audio/x-aiff'   

'.au': 'audio/basic'   

'.avi': 'video/x-msvideo'   

'.bat': 'text/plain'   

'.bcpio' : 'application/x-bcpio'   

'.bin': 'application/octet-stream'   

'.bmp': 'image/x-ms-bmp'   

'.c': 'text/plain'

'.cdf': 'application/x-cdf'   

'.cdf': 'application/x-netcdf'   

'.cpio': 'application/x-cpio'   

'.csh': 'application/x-csh'   

'.css': 'text/css'   

'.dll': 'application/octet-stream'   

'.doc': 'application/msword'   

'.dot': 'application/msword'   

'.dvi': 'application/x-dvi'   

'.eml': 'message/rfc822'   

'.eps': 'application/postscript'   

'.etx' : 'text/x-setext'   

'.exe': 'application/octet-stream'   

'.gif': 'image/gif'   

'.gtar': 'application/x-gtar'   

'.h': 'text/plain'   

'.hdf': 'application/x-hdf'   

'.htm': 'text/html'   

'.html': 'text/html'   

'.ief': 'image/ief'   

'.jpe': 'image/jpeg'   

'.jpeg': 'image/jpeg'   

'.jpg': 'image/jpeg'  

'.js': 'application/x-javascript'   

'.ksh': 'text/plain'   

'.latex' : 'application/x-latex'   

'.m1v': 'video/mpeg'   

'.man': 'application/x-troff-man'   

'.me': 'application/x-troff-me'   

'.mht' : 'message/rfc822'   

'.mhtml' : 'message/rfc822'   

'.mif': 'application/x-mif'   

'.mov': 'video/quicktime'   

'.movie' : 'video/x-sgi-movie'   

'.mp2': 'audio/mpeg'   

'.mp3': 'audio/mpeg'   

'.mpa' : 'video/mpeg'   

'.mpe': 'video/mpeg'   

'.mpeg': 'video/mpeg'   

'.mpg': 'video/mpeg'   

'.ms': 'application/x-troff-ms'   

'.nc' : 'application/x-netcdf'   

'.nws': 'message/rfc822'   

'.o': 'application/octet-stream'   

'.obj': 'application/octet-stream'   

'.oda': 'application/oda'   

'.p12' : 'application/x-pkcs12'   

'.p7c': 'application/pkcs7-mime'   

'.pbm': 'image/x-portable-bitmap'   

'.pdf': 'application/pdf'   

'.pfx': 'application/x-pkcs12'   

'.pgm': 'image/x-portable-graymap'   

'.pl': 'text/plain'   

'.png': 'image/png'   

'.pnm': 'image/x-portable-anymap'   

'.pot': 'application/vnd.ms-powerpoint'   

'.ppa': 'application/vnd.ms-powerpoint'   

'.ppm': 'image/x-portable-pixmap'   

'.pps': 'application/vnd.ms-powerpoint'   

'.ppt': 'application/vnd.ms-powerpoint'   

'.ps': 'application/postscript'   

'.pwz': 'application/vnd.ms-powerpoint'   

'.py': 'text/x-python'   

'.pyc': 'application/x-python-code'   

'.pyo' : 'application/x-python-code'   

'.qt': 'video/quicktime'   

'.ra' : 'audio/x-pn-realaudio'   

'.ram' : 'application/x-pn-realaudio'   

'.ras' : 'image/x-cmu-raster'   

'.rdf': 'application/xml'   

'.rgb' : 'image/x-rgb'   

'.roff': 'application/x-troff'   

'.rtx' : 'text/richtext'   

'.sgm': 'text/x-sgml'   

'.sgml': 'text/x-sgml'   

'.sh': 'application/x-sh'   

'.shar' : 'application/x-shar'   

'.snd' : 'audio/basic'   

'.so' : 'application/octet-stream'   

'.src': 'application/x-wais-source'   

'.sv4cpio': 'application/x-sv4cpio'   

'.sv4crc' : 'application/x-sv4crc'   

'.swf': 'application/x-shockwave-flash'   

'.t' : 'application/x-troff'   

'.tar': 'application/x-tar'   

'.tcl' : 'application/x-tcl'   

'.tex' : 'application/x-tex'   

'.texi': 'application/x-texinfo'   

'.texinfo': 'application/x-texinfo'   

'.tif' : 'image/tiff'   

'.tiff': 'image/tiff'   

'.tr': 'application/x-troff'   

'.tsv': 'text/tab-separated-values'   

'.txt': 'text/plain'   

'.ustar' : 'application/x-ustar'   

 

'.vcf': 'text/x-vcard'   

'.wav': 'audio/x-wav'   

'.wiz': 'application/msword'   

'.wsdl': 'application/xml'   

'.xbm': 'image/x-xbitmap'   

'.xlb': 'application/vnd.ms-excel'   

 

# Duplicates

'.xls': 'application/excel'   

'.xls': 'application/vnd.ms-excel'   

'.xml' : 'text/xml'   

'.xpdl': 'application/xml'   

'.xpm': 'image/x-xpixmap'   

'.xsl': 'application/xml'   

'.xwd': 'image/x-xwindowdump'   

'.zip': 'application/zip'

 

  • 4
    点赞
  • 0
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:撸撸猫 设计师:马嘣嘣 返回首页

打赏作者

Remoa

您的鼓励将是我创作的巨大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值