`

springmvc上传

 
阅读更多

第一步,导入spring jar(commons-logging-1.0.4.jar、上传组件commons-fileupload.jarcommons-io.jar)

 

第二步,项目配置文件web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>GBK</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

 

第三步,springMVC配置文件springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
		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"
	>

	<!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
	<context:component-scan base-package="com.test.controller" />

	<!--对模型视图名称的解析,即在模型视图名称添加前后缀 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix" value="/jsp/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<!-- 处理文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="gbk" /> <!-- 默认编码 (ISO-8859-1) -->
		<property name="maxInMemorySize" value="10240" /> <!-- 最大内存大小 (10240) -->
		<property name="uploadTempDir" value="/uploadFile/" /> <!-- 上传后的目录名 -->
		<property name="maxUploadSize" value="-1" /> <!-- 最大文件大小,-1为无限制 -->
	</bean>

</beans>

 

第四步,控制器FileUploadController.java

package com.test.controller;

import java.io.File;
import java.util.Date;

import javax.servlet.ServletContext;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Controller
public class FileUploadController implements ServletContextAware {

	private ServletContext servletContext;

	public ServletContext getServletContext() {
		return servletContext;
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	// 这里@RequestParam("file")必须要有(不清楚为什么),必须是post请求
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String handleUploadData(@RequestParam("file") CommonsMultipartFile file, Model model) {
		String fileName = "";
		String message = "";
		if (!file.isEmpty()) {
			String path = this.servletContext.getRealPath("/temp");// 获取本地存储路径
			System.out.println(path);
			fileName = file.getOriginalFilename();
			String[] fileArray = fileName.split("\\.");
			File file2 = new File(path + "\\" + fileArray[0] + "_" + new Date().getTime() + "." + fileArray[1]);
			try {
				file.getFileItem().write(file2);
			} catch (Exception e) {
				e.printStackTrace();
				message = "上传失败!";
			}
			message = "上传成功!";
		} else {
			message = "没有文件可上传!";
		}
		model.addAttribute("fileName", fileName);
		model.addAttribute("message", message);

		return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/uploadFile.jsp";
	}
}

 

前台页面/uploadFile.jsp

<%@ page language="java" pageEncoding="gbk"%>
<html>
<head>
<title>测试springmvc中上传的实现</title>
</head>
<body>
	<form action="upload" method="post" enctype="multipart/form-data">
		<input type="file" name="file" /> <input type="submit" value="上传"/>
	</form>
	<br>
	<h1>
		<%
			String message = request.getParameter("message");
			String fileName = request.getParameter("fileName");
			fileName = fileName == null ? "" : fileName;
			if (!"".equals(fileName)) {
				fileName = new String(fileName.getBytes("iso8859-1"), "GBK");
			}
			if(message != null){
		%>
			文件:
		<%
			}
		%>
		<%=fileName %>&nbsp;
		<%
		
			message = message == null ? "" : message;
			if (!"".equals(message)) {
				message = new String(message.getBytes("iso8859-1"), "GBK");
			}
		%>
		<%=message%>
	</h1>
</body>
</html>

 

WebContent下面新建tempuploadFile文件夹,其中,temp是用于存放上传的文件,uploadFile是临时存放上传的文件一部分(相当于缓存)

浏览器输入:

http://127.0.0.1:9900/springmvc_007_upload/uploadFile.jsp

页面显示:

 

  • 大小: 14.3 KB
  • 大小: 5.4 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics