-
效果图如下:访问:localhost:8080/file/show
-
构建Springboot项目使用代码生成器,引入相关jar包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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>fileupload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>fileupload</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<mysql.version>5.1.47</mysql.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter 分页 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.nekohtml/nekohtml -->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<configurationFile>src/main/resources/mybatis/generator-config.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>文件上传下载</title>
</head>
<body>
<center>
<form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input type="file" name="file" /></td>
</tr>
<tr>
<td><input type="submit" value="提交"/></td>
</tr>
<hr>
</table>
</form>
<table>
<tr th:each="file:${file}">
<td> <a th:href="@{/file/show}" th:text="${file.filename}"></a></td>
<td><a th:href="@{'/file/get?id='+${file.id}}" ><button>下载</button></a></td>
</tr>
</table>
</center>
</body>
</html>
FileController
package com.example.fileupload.upload;
import com.example.fileupload.domain.Pic;
import org.apache.tomcat.jni.File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
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 java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
@RequestMapping("/file")
@Controller
public class FileController {
@Autowired
private FileService fileService;
@RequestMapping("")
public String show(){
return "index";
}
/**
* 文件上传
* */
@RequestMapping(value = "/upload",method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
Pic pic=new Pic();
if(multipartFile!=null){
pic.setContent(multipartFile.getBytes());
pic.setFilename(multipartFile.getOriginalFilename());
pic.setFilesize(new BigDecimal(multipartFile.getSize()));
pic.setContenttype(multipartFile.getContentType());
pic.setPicaddress(multipartFile.getOriginalFilename());
int updated=fileService.save(pic);
}else {
System.out.println("没有文件");
}
Files.write(Paths.get("E:","/myFile/",multipartFile.getOriginalFilename()),multipartFile.getBytes());
return "redirect:/file/show";
}
/**
* 将数据库中的所有文件显示在列表上
* */
@RequestMapping(value = "/show",method = RequestMethod.GET)
public String show(Model model){
List<Pic> pic=fileService.list();
model.addAttribute("file",pic);
return "index";
}
/**
* 实现下载功能
* */
@GetMapping(value = "/get")
public ResponseEntity<ByteArrayResource> get(@RequestParam("id") String id){
Pic pic=fileService.find(id);
return ResponseEntity.ok()
.contentLength(pic.getFilesize().longValue())
.contentType(MediaType.parseMediaType(pic.getContenttype()))
.body(new ByteArrayResource(pic.getContent()));
}
}
sql数据库
DROP TABLE IF EXISTS `pic`;
CREATE TABLE `pic` (
`id` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`filename` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`content` longblob NULL,
`filesize` decimal(20, 0) NULL DEFAULT NULL,
`contenttype` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
FileService
package com.example.fileupload.upload;
import com.example.fileupload.domain.Pic;
import java.util.List;
public interface FileService {
int save(Pic pic);
List<Pic> list();
Pic find(String id);
}
实体类、mapper.xml都是Mybatis代码生成器生成的
application.yml配置文件
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=yes&characterEncoding=UTF-8&useSSL=false
username: root
password: Rjxy
driver-class-name: com.mysql.jdbc.Driver
thymeleaf:
mode: LEGACYHTML5
cache: false
mybatis:
mapper-locations: classpath:/mybatis/mapper/*.xml
configuration:
map-underscore-to-camel-case: true
logging:
level:
com.example.fileupload.mapper: DEBUG
Generator-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="MySQLTables" targetRuntime="MyBatis3">
<!--Official Plugins-->
<!--Generate equals and hash code-->
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=yes&characterEncoding=UTF-8&useSSL=false"
userId="root"
password="123456">
<property name="useInformationSchema" value="true"/>
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<javaModelGenerator targetPackage="com.example.fileupload.domain" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources/mybatis">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.fileupload.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table schema="test" tableName="pic" domainObjectName="Pic">
<generatedKey column="id" sqlStatement="select uuid_short()" identity="false"/>
</table>
</context>
</generatorConfiguration>
Congfigure.java:配置springboot访问图片的默认路径,可以直接访问图片的地址
package com.example.fileupload.util;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class Configure extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 指定到E盘下的myFile文件夹
registry.addResourceHandler("/myFile/**").addResourceLocations("file:E:/myFile/").addResourceLocations("classpath:/resources/");
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}
码云仓库地址:https://gitee.com/Marlon_Brando/tableandupload