关联jar包:
<!-- apache commons jar -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io-version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload-version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${org.apache.commons-version}</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <!-- 配置启动 Spring IOC 容器的 Listener --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 配置字符编码 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置 HiddenHttpMethodFilter: 把 POST 请求转为 DELETE、PUT 请求 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置 DispatcherServlet --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
<!-- 设置自动扫描的包 --> <context:component-scan base-package="com.dongly.bookstores" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> </context:component-scan> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 上传文件的设置 ,maxUploadSize=-1,表示无穷大。uploadTempDir为上传的临时目录 --> <!-- 在这个bean中的id一定要叫multipartResolver,不然会报错,在在文件上传的时候还需要两个jar文件 com.springsource.org.apache.commons.fileupload-1.2.0.jar com.springsource.org.apache.commons.io-1.4.0.jar --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 配置文件的编码方式 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 配置文件最大值 5m--> <property name="maxUploadSize" value="5400000"></property> <!-- 最大内存大小 (默认 10240)--> <property name="maxInMemorySize" value="10240"></property> <!-- 配置临时目录 --> <property name="uploadTempDir" value="fileUpload/temp"></property> </bean> <!-- default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler, 它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的 Servlet 处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理 一般 WEB 应用服务器默认的 Servlet 的名称都是 default. 若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定 --> <mvc:default-servlet-handler /> <!-- 解决静态页面加载问题 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 可以使用 path 直接导航到 /WEB-INF/views/view-name.jsp 页面 --> <mvc:view-controller path="/file1" view-name="/singleUploadFile"/>
package com.dongly.bookstores.Controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@Controller
public class FileUploadController {
private Logger logger = LoggerFactory.getLogger(FileUploadController.class);
@RequestMapping("/singleUploadFile")
public String singleUploadFile(HttpServletRequest request, HttpServletResponse response) {
// 创建一个通用的多部分解析器
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getServletContext());
//判断 request 是否有文件上传,即多部分请求
if (commonsMultipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) (request);
// 取得request中的所有文件名
Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
while (fileNames.hasNext()) {
// 取得上传文件
MultipartFile file = multipartHttpServletRequest.getFile(fileNames.next());
if (file != null) {
// 取得当前上传文件的文件名称
String fileName = file.getOriginalFilename();
// 如果名称不为“”,说明该文件存在,否则说明该文件不存在
if (fileName.trim() != "") {
// 重命名上传后的文件名
String newFileName = System.currentTimeMillis() + fileName;
String realPath = request.getServletContext().getRealPath("/upload");
// 定义上传路径
String newPath = realPath + File.separator + newFileName;
File path = new File(newPath);
if (!path.exists()) {
path.mkdirs();
}
String fileUrl = newPath.replaceAll("\\\\", "/").substring(newPath.indexOf("upload"));
try {
file.transferTo(path);
logger.info("fileUrl ===>>>" + fileUrl);
request.setAttribute("fileUrl", fileUrl);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
}
}
}
return "fileUpload2";
}
@RequestMapping("/batchUploadFile")
public String batchUploadFile(@RequestParam("file") CommonsMultipartFile files[],
HttpServletRequest request, Map<String,Object> model){
List<String> filePaths = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
if(files[i] != null){
// 上传位置
String realPath = request.getServletContext().getRealPath("/img");
File path = new File(realPath);
if (!path.exists()) {
path.mkdirs();
}
//获得原始文件
String fileName = files[i].getOriginalFilename();
logger.info("原始文件 == > " + fileName);
if (fileName.trim() != "") {
String newFileName = System.currentTimeMillis() + fileName;
String newPath = path + File.separator + newFileName;
String fileUrl = newPath.replaceAll("\\\\", "/").substring(newPath.indexOf("img"));
try {
files[i].transferTo(new File(newPath));
filePaths.add(fileUrl);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
}
}
model.put("fileList", filePaths);
return "batchUploadFile";
}
}
<%@ 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>
<center>
<form action="singleUploadFile"
method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上 传" />
</form>
<h5>上传结果:</h5>
<img alt="暂无图片" src="${fileUrl}" />
<a href="${fileUrl}">下载图片</a>
</center>
</body>
</html>
<%@ 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">
<title>Insert title here</title>
</head>
<body>
<center>
<form action="batchUploadFile"
method="post" enctype="multipart/form-data">
<input type="file" name="file" /> <br>
<input type="file" name="file" /> <br>
<input type="file" name="file" /> <br>
<input type="submit" value="上 传" />
</form>
<h5>上传结果:</h5>
<c:forEach items="${fileList }" var="fileName">
<img alt="暂无图片" src="${fileName}" />
<a href="${fileName}">下载图片</a>
</c:forEach>
</center>
</body>
</html>
本文详细介绍了如何将Java Web应用与Spring MVC框架整合,包括配置启动Spring IOC容器、设置自动扫描的包、配置视图解析器、上传文件的设置以及处理静态页面加载等问题。
781

被折叠的 条评论
为什么被折叠?



