项目实现功能
把学号存放到txt文本里面,上传到浏览器,然后里面学生的学号命名学生传送来的照片
项目实现过程
pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<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.xiaonan.school</groupId>
<artifactId>SchoolNucleicAcid</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SchoolNucleicAcid Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.1</version>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- ServletAPI -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- Spring5和Thymeleaf整合包 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resource</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<finalName>SchoolNucleicAcid</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
springmvc.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自动扫描包 -->
<context:component-scan base-package="com.xiaonan.school"/>
<!-- 配置Thymeleaf视图解析器 -->
<bean id="viewResolver"
class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean
class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- 视图前缀 -->
<property name="prefix" value="/WEB-INF/templates/"/>
<!-- 视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
</bean>
</property>
</bean>
</property>
</bean>
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
</beans>
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
<!-- 配置springMVC的编码过滤器 -->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<!-- 配置SpringMVC的前端控制器,对浏览器发送的请求统一进行处理 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 通过初始化参数指定SpringMVC配置文件的位置和名称 -->
<init-param>
<!-- contextConfigLocation为固定值 -->
<param-name>contextConfigLocation</param-name>
<!-- 使用classpath:表示从类路径查找配置文件,例如maven工程中的
src/main/resources -->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--
作为框架的核心组件,在启动过程中有大量的初始化操作要做
而这些操作放在第一次请求时才执行会严重影响访问速度
因此需要通过此标签将启动控制DispatcherServlet的初始化时间提前到服务器启动时
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!--
设置springMVC的核心控制器所能处理的请求的请求路径
/所匹配的请求可以是/login或.html或.js或.css方式的请求路径
但是/不能匹配.jsp请求路径的请求
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Controller类
@Controller
@RequestMapping("/xiaonan")
public class ControllerClass {
@RequestMapping("/up")
public String XiaonanUp(MultipartFile text, HttpSession session) throws IOException {
//获取上传的文件的文件名
String fileName = text.getOriginalFilename();
//获取服务器中text目录的路径
ServletContext servletContext = session.getServletContext();
String textPath = servletContext.getRealPath("text");
File file = new File(textPath);
if(!file.exists()){
file.mkdir();
}
String finalPath = textPath + File.separator + fileName;
//实现上传功能
text.transferTo(new File(finalPath));
return "success";
}
@RequestMapping("/list")
public String XiaonanList(HttpSession session, Model model) throws IOException {
ServletContext servletContext = session.getServletContext();
String text = servletContext.getRealPath("text");
String textPath = text + File.separator + "软件工程40班.txt";
System.out.println("文本路径位置"+textPath);
List<Student> studentList=new ArrayList<Student>();
File file = new File(textPath);
BufferedReader reader = null;
String tempString = null;
int flag =1;
try {
// System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
while ((tempString = reader.readLine()) != null) {
System.out.println("Line"+ flag + ":" +tempString);
//学生名字存入list集合
studentList.add(new Student(flag,tempString));
flag++ ;
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
model.addAttribute("studentlist",studentList);
return "list";
}
@RequestMapping(value = "/studentup/{studentid}", method = RequestMethod.POST)
public String StudentUp(@PathVariable("studentid") String studentid, MultipartFile photo, HttpSession session)throws IOException{
System.out.println("学号"+studentid);
//获取上传的文件的文件名
String fileName = photo.getOriginalFilename();
fileName=studentid+".jpg";
//获取服务器中photo目录的路径
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("photo");
File file = new File(photoPath);
if(!file.exists()){
file.mkdir();
}
String finalPath = photoPath + File.separator + fileName;
//实现上传功能
photo.transferTo(new File(finalPath));
return "success";
}
}
Student类
public class Student {
int id;
String studentID;
public int getId() {
return id;
}
public String getStudentID() {
return studentID;
}
public void setId(int id) {
this.id = id;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", studentID='" + studentID + '\'' +
'}';
}
public Student() {
}
public Student(int id, String studentID) {
this.id = id;
this.studentID = studentID;
}
}
index,html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>收集核酸截图 by:南香香</title>
</head>
<body>
上传名单
<form th:action="@{/xiaonan/up}" method="post" enctype="multipart/form-data">
文本:<input type="file" name="text"><br>
<input type="submit" value="上传">
</form>
<a th:href="@{/xiaonan/list}">生成表格</a>
</body>
</html>
list.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>班级学生展示</title>
</head>
<body>
<table border="1" cellpadding="0" cellspacing="0" style="text-align:
center;" id="dataTable">
<tr>
<th colspan="5">软件40班核酸收集</th>
</tr>
<tr>
<th>学号</th>
<th>上传文件</th>
</tr>
<tr th:each="student : ${studentlist}">
<td th:text="${student.studentID}" ></td>
<td>
<form name="xiaonan" id="xiaonanform" action="/xiaonan/studentup/" method="post" enctype="multipart/form-data">
核酸截图:<input type="file" name="photo">
<!--<input th:class="${student.studentID}" onclick="xiaonanup(this)" type="submit" value="上传">-->
<input th:onclick="xiaonanup([[${student.studentID}]]);" type="button" value="上传">
</form>
</td>
</tr>
</table>
<script type="text/javascript">
// var actionpath=document.getElementById("xiaonanform");
// function xiaonanup(that) {
// console.log(that)
// var ps = that.getAttribute("class")
// alert("/xiaonan/studentup/"+ps)
// actionpath.action="/xiaonan/studentup/"+ps;
// alert(actionpath.action);
// }
var actionpath=document.getElementById("xiaonanform");
function xiaonanup(id) {
actionpath.action += id;
document.xiaonan.action +=id;
actionpath.submit()
}
</script>
</body>
</html>
以上是我全部实现的过程,可能会有代码冗余,也可能会有瑕疵出现,多多包涵
springmvc下载和上传模板
@Controller
public class FileUpAndDownController {
@RequestMapping("/test/down")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws
IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/img/1.png");
//创建输入流
InputStream is = new FileInputStream(realPath);
//创建字节数组
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String, String> headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
// headers.add("Content-Disposition", "attachment;filename=1.png");
//中文识别不了
headers.add("Content-Disposition", "attachment;filename=白石丽.jpg");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers,
statusCode);
//关闭输入流
is.close();
return responseEntity;
}
@RequestMapping("/test/up")
public String testUp(MultipartFile photo, HttpSession session) throws
IOException {
//获取上传的文件的文件名
String fileName = photo.getOriginalFilename();
//处理文件重名问题
String hzName = fileName.substring(fileName.lastIndexOf("."));
fileName = UUID.randomUUID().toString() + hzName;
//获取服务器中photo目录的路径
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("photo");
File file = new File(photoPath);
if(!file.exists()){
file.mkdir();
}
String finalPath = photoPath + File.separator + fileName;
//实现上传功能
photo.transferTo(new File(finalPath));
return "success";
}
}
文章全部是本人原创,请勿转发,谢谢配合,版权所有-南香香-你会喜欢我吗