SpringMVC File Upload

这次主要是公司内部使用的项目,需要做到可以上传,并且统计count的数字。

使用的是springmvc

先来看maven

<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>cn.edu.ken.mavenweb</groupId>
	<artifactId>mavenweb</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>mavenweb Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<springversion>4.2.1.RELEASE</springversion>
		<junitversion>4.8.1</junitversion>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.6.1</version>
		</dependency>
		<dependency>
			<groupId>org.apache.derby</groupId>
			<artifactId>derby</artifactId>
			<version>10.11.1.1</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junitversion}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jms</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${springversion}</version>
			<type>jar</type>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.1</version>
		</dependency>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>xom</groupId>
			<artifactId>xom</artifactId>
			<version>1.2.5</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.6.1</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>1.9.13</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.3.0</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.0.8</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.3</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
			<version>1.6</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>mavenweb</finalName>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.mybatis.generator</groupId>
					<artifactId>mybatis-generator-maven-plugin</artifactId>
					<version>1.3.2</version>
					<configuration>
						<configurationFile>generatorConfig.xml</configurationFile>
						<verbose>true</verbose>
						<overwrite>true</overwrite>
					</configuration>
					<executions>
						<execution>
							<id>Generate MyBatis Artifacts</id>
							<goals>
								<goal>generate</goal>
							</goals>
						</execution>
					</executions>
					<dependencies>
						<dependency>
							<groupId>org.mybatis.generator</groupId>
							<artifactId>mybatis-generator-core</artifactId>
							<version>1.3.2</version>
						</dependency>
					</dependencies>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>


然后是SpringMVC配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
        http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-3.0.xsd   
        http://www.springframework.org/schema/mvc   
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd   
        http://www.springframework.org/schema/tx   
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
	default-autowire="byName">
	<!-- 激活spring的注解. -->
	<context:annotation-config />
	<mvc:annotation-driven />
	<context:component-scan base-package="cn.edu.ken" />

	<mvc:interceptors>
		<bean class="cn.edu.ken.commons.interceptor.MyInteceptor" />
	</mvc:interceptors>
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView"></property>
	</bean>

</beans> 

最后是Controller和画面

package cn.edu.ken.business.controller;

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

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.edu.ken.business.service.UserService;
import cn.edu.ken.commons.util.FileHelper;
import cn.edu.ken.commons.util.Page;
import cn.edu.ken.mybatis.model.User;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource(name = "userService")
	private UserService userService;

	@RequestMapping("/login")
	public String login(User user, Model model, HttpServletRequest request) {
		int rvLogin = userService.login(user);
		if (rvLogin == 1) {
			return "users/success";
		} else {
			return "users/failed";
		}
	}

	@RequestMapping("/add")
	public String add(User user, HttpServletRequest request) {
		userService.addUser(user);

		return "users/search";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/upload")
	public String handleUploadProcess(
			@RequestParam("imageFile") MultipartFile file, User user,
			HttpServletRequest request) throws Exception {
		// validator.validate(file);
		String url = "/Users/ken/Downloads/dev/ws/bitbucketOA/src/"
				+ request.getContextPath() + "/temp/";
		File dir = new File(url);
		if (!dir.exists() && !dir.isDirectory()) {
			System.out.println("//不存在");
			dir.mkdir();
		}
		String path = url + file.getOriginalFilename();
		File fileName = new File(path);
		if (!fileName.exists()) {
			try {
				fileName.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("||||" + url);
		FileHelper.save(path, file.getBytes());
		userService.addUser(user);
		return "users/search";
	}

	@RequestMapping(value = "/preupdate/{iduser}", method = RequestMethod.GET)
	public String preupdate(@PathVariable(value = "iduser") Integer iduser,
			Model model) {
		System.out.println("=======" + iduser);
		User user = userService.searchById(iduser);
		if (user != null)
			model.addAttribute("user", user);
		return "users/update";
	}

	@RequestMapping("/update")
	public String update(User user) {
		userService.updateUser(user);
		return "users/search";
	}

	/**
	 * 
	 * 
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping("/addsearch")
	public String addSearch(User user, Model model) {
		userService.addUser(user);
		List<User> users = userService.searchByUser(user);
		model.addAttribute("users", users);
		return "users/search";
	}

	@RequestMapping("/search")
	public String searchByCondition(User user, Model model) {
		List<User> users = userService.searchByCondition(user);
		model.addAttribute("users", users);
		user = null;
		return "users/search";
	}

	@RequestMapping("/findpage")
	public String searchByPage(Model model) {
		Page<User> page = userService.findByPage();
		model.addAttribute("users", page.getResults());
		model.addAttribute("totalrecord", page.getTotalRecord());
		model.addAttribute("pageno", page.getPageNo());
		return "users/search";
	}

	@RequestMapping(value = "/deleteids")
	public String deleteByIds(HttpServletRequest request) {
		String[] ids = request.getParameterValues("ids");
		for (int i = 0; i < ids.length; i++) {
			System.out.println(ids[i]);
			userService.deleteUser(Integer.valueOf(ids[i]));
		}

		return "users/search";
	}

}

package cn.edu.ken.commons.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileHelper {
	public static void save(String path, byte[] bytes) {
		System.out.println(bytes);
		FileOutputStream fos = null;
		File file = new File(path);
		
		try {
			fos = new FileOutputStream(file);
			byte[] numBytes = bytes;
			fos.write(numBytes);
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

<%@ page contentType="text/html;charset=utf-8"%>
<html>
<body>
	<h2>添加用户</h2>
	<form method="post" action="<%=request.getContextPath()%>/user/upload"
		enctype="multipart/form-data">
		<table>
			<tr>
				<td>username</td>
				<td><input type="text" name="username" id="username"></td>
			</tr>
			<tr>
				<td>password</td>
				<td><input type="text" name="password" id="password"></td>
			</tr>
			<tr>
				<td>file</td>
				<td><input type="file" name="imageFile" /></td>
			</tr>

		</table>
		<input type="submit" name="register" value="录入">
	</form>
</body>
</html>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值