>

本例所使用的例子为txt文件sbf282.com:,我们将实

- 编辑:澳门博发娱乐官网 -

本例所使用的例子为txt文件sbf282.com:,我们将实

buildscript { ext { springBootVersion = '2.0.3.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") }}apply plugin: 'java'apply plugin: 'eclipse'apply plugin: 'org.springframework.boot'apply plugin: 'io.spring.dependency-management'group = 'com.example'version = '0.0.1-SNAPSHOT'sourceCompatibility = 1.8repositories { mavenCentral()}dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test')}
<!DOCTYPE HTML><html xmlns:th="http://www.thymeleaf.org"><head> <title>Upload files by Spring Boot</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="http://www.jfrhdhzpgs.com/uploads/allimg/191005/230501Kb-0.jpg"></script> <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script></head><body><center> <br><br><br> <div style="width:600px"> <div > <h3 >文件上传</h3> </div> <div > <form role="form" method="POST" action="/upload" enctype="multipart/form-data"> <div style="width:600px"> <label for="upload" >选择文件</label> <div > <input type="file" name="file" /> </div> </div> <div > <div> <button type="submit" >提交</button> <input type="reset" value="重置" /> </div> </div> </form> </div> </div></center></body></html>

我们在原有的Spring Boot项目上进行修改,该Spring Boot项目就是博客:Spring Boot入门提交表单并存入MySQL数据库中的Spring Boot项目,也可以参看其Github地址: 。该项目的完整结构如下图:

sbf282.com 1访问10次

package com.form.formIntoMySQL.entity;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;@Entity // This tells Hibernate to make a table out of this classpublic class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; private String name; private Integer age; private String gender; private String email; private String city; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCity() { return city; } public void setCity(String city) { this.city = city; }}

sbf282.com 2文件下载

  • 利用Spring Boot的MultipartFile实现文件的上传;
  • 利用Spring MVC实现整个文件上传流程的控制;
  • 利用javacsv API实现CSV文件的读取;
  • 利用JavaScript实现CSV文件的数据预览

加入表单验证需要修改以上三个红线框内的文件。 首先是User.java,在代码中加入表单验证的限制条件,其代码如下:

buildscript { ext { springBootVersion = '2.0.3.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") }}apply plugin: 'java'apply plugin: 'eclipse'apply plugin: 'org.springframework.boot'apply plugin: 'io.spring.dependency-management'group = 'com.example'version = '0.0.1-SNAPSHOT'sourceCompatibility = 1.8repositories { mavenCentral()}dependencies { compile('org.springframework.boot:spring-boot-starter-web') // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '2.0.1.RELEASE'}

接着需要配置静态资源,即相关的网页,我们项目中的网页采用Thymeleaf视图来实现,其中greeting.html为初始进去的网页,其代码如下:

我们只需要创建一个控制器(Controler)文件,即Controller目录下的File_Download.java,其完整目录如下:

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"></head><body><center> <br><br> <h2>文件上传状态</h2> <br><br> <div style="width:1000px"> <div > <h3 >文件上传</h3> </div> <div > <div th:if="${message}"> <h3 th:text="${message}"/> </div> </div> </div> <a href="/upload"><button >返回文件上传</button></a> <a href="/review"><button >数据预览</button></a> </center></body></html>

前者需要用到JavaScript方面的知识,对于熟悉JS的读者来说,这并不是困难的事情,但是表单验证处理起来比较麻烦,也容易遗漏掉需要验证的条件。采用Spring Boot原生方法进行表单验证比较方便,但是需要熟悉Spring Boot方面的知识。

这样我们就用Spring Boot实现了页面访问量的统计功能。

点击Submit按钮,将会跳转到结果显示页面,如下图:

build.gradle文件的代码如下:

主要是两部分的内容,一部分是Controller,一部分是view文件。UploadController.java是控制器,其代码如下:

sbf282.com 3表单验证通过

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>访问统计</title> <script th:inline="javascript"> function load(){ var count = [[${count}]]; document.getElementById.innerHTML = count.toString(); } </script></head><body onload="load()"><h1>Hello, world!</h1><p>&emsp;&emsp;本页面已被访问次。</p></body></html>
buildscript { ext { springBootVersion = '2.0.1.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") }}apply plugin: 'java'apply plugin: 'eclipse'apply plugin: 'org.springframework.boot'apply plugin: 'io.spring.dependency-management'group = 'com.form'version = '0.0.1-SNAPSHOT'sourceCompatibility = 1.8repositories { mavenCentral()}dependencies { // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.0.RELEASE' // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '2.0.1.RELEASE' // JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) compile 'org.springframework.boot:spring-boot-starter-data-jpa' // Use MySQL Connector-J compile 'mysql:mysql-connector-java' // https://mvnrepository.com/artifact/junit/junit testCompile group: 'junit', name: 'junit', version: '4.12'}

这样我们就完成了Spring Boot的文件下载功能。什么?这样就搞定了?是的,就是这么简单,因为只实现了文件下载功能。具体的代码留给读者好好分析哦~~ 写完代码并不是我们的最终目的,我们还差最后一步,那就是测试!测试,真的相当重要啊~ 运行Spring Boot项目后,在浏览器中输入: , 你会发现什么?那就是你的浏览器已经开始下载E盘music_eg目录下的某一个文件啦(前提是E盘中存在music_eg目录,当然里面还得有文件,本例仅作为测试),如下图所示:

好不容易写完了项目,不测试一把,对不起观众啊。 启动Spring Boot项目,在浏览器中输入:

当表单验证通过后,我们就能进行result.html结果显示页面,如下图:

控制器文件VisitController.java文件的代码如下:

sbf282.com 4formIntoMySQL项目完整目录

sbf282.com 5项目结构

package com.hello.upload.Controller;import java.io.IOException;import java.util.ArrayList;import java.util.List;import com.csvreader.CsvReader;/*** readCSV类:实现CSV文件内容的读取 */public class readCSV { // 参数:文件路径 private String file_path; // 构造函数 readCSV(){} readCSV(String file_path){ this.file_path = file_path; } // getter and setter public String getFile_path() { return file_path; } public void setFile_path(String file_path) { this.file_path = file_path; } // read()函数实现具体的读取CSV文件内容的方法 public List<String> read() { List<String> result = new ArrayList<>(); try { // 创建CSV读对象 CsvReader csvReader = new CsvReader(file_path); while (csvReader.readRecord{ // 读取每一行数据,以逗号分开 // System.out.println(csvReader.getRawRecord; result.add(csvReader.getRawRecord; } csvReader.close(); return result; } catch (IOException e) { e.printStackTrace(); return result; } }}

我们需要对上述程序进行测试,重点在于表单验证功能。在浏览器中输入: ,什么都不输入,直接点击Submit按钮,显示如下:

sbf282.com 6访问1次

package com.form.formIntoMySQL;import org.springframework.data.repository.CrudRepository;import com.form.formIntoMySQL.entity.User;// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository// CRUD refers Create, Read, Update, Deletepublic interface UserRepository extends CrudRepository<User, Long> {}

注意:本人现已开通两个微信公众号: 因为Python(微信号为:python_math)以及轻松学会Python爬虫(微信号为:easy_web_scrape), 欢迎大家关注哦~~

package com.hello.upload.Controller;import java.util.*;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import org.springframework.web.servlet.mvc.support.RedirectAttributes;@Controllerpublic class UploadController{ private String filename; //Save the uploaded file to this folder private static String UPLOADED_FOLDER = "E://upload/src/main/resources/static/images/"; /* **文件上传页面 */ @GetMapping("/upload") public String upload(){ return "upload"; } @PostMapping("/upload") public String singleFileUpload(@RequestParam MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty { redirectAttributes.addFlashAttribute("message", "文件为空! 请选择非空文件上传!"); return "redirect:/uploadStatus"; } try { // 获取文件并保存到指定文件夹中 byte[] bytes = file.getBytes(); filename = file.getOriginalFilename(); Path path = Paths.get(UPLOADED_FOLDER + filename); Files.write(path, bytes); redirectAttributes.addFlashAttribute("message", "您已成功上传 '" + filename + "', 该文件大小约为 " +bytes.length/1024+" KB."); } catch (IOException e) { e.printStackTrace(); } return "redirect:/uploadStatus"; } /* ** 文件上传信息处理页面 */ @GetMapping("/uploadStatus") public String uploadStatus(){ return "uploadStatus"; } /* ** 数据预览页面: 支持CSV文件和部分图片格式的预览 */ @GetMapping("/review") public String review(Map<String, Object> map) { map.put("filename", filename); String filetype = filename.split[1]; map.put("filetype",filetype); System.out.println; if(filetype.equals { readCSV read_csv = new readCSV(UPLOADED_FOLDER + filename); List<String> result = read_csv.read(); map.put("result", result); } return "review"; }}

在greetingSubmit()方法中我们加入了表单验证@Valid,如果出现表单验证错误,则返回greeting.html页面,并显示错误信息,如果表单验证成功,则返回result.html页面。 最后需要对展示验证表单错误信息的网页greeting.html进行修改,其代码如下:

视图文件index.HTML的代码如下:

接着在com.form.formIntoMySQL下新建UserReposittory.java,来实现CrudRepositoty接口,其代码如下:

本文由胜博发-编程发布,转载请注明来源:本例所使用的例子为txt文件sbf282.com:,我们将实