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>
<artifactId>spring-boot-jpa-file</artifactId>
<name>spring-boot-file</name>
<description>spring-boot-file</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
</project>
downloadController.java
package com.example.demo.web;
import com.example.demo.dao.po.FilePo;
import com.example.demo.dao.FileDao;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@RestController
@ApiModel("文件下载")
@RequestMapping(value = "/frontapi/download")
public class testFileController {
@Autowired
private FileDao fileDao;
@ApiOperation(value = "文件下载", notes = "文件下载")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "文件ID", required = true, dataType = "Integer", paramType = "query"),
@ApiImplicitParam(name = "outPath", value = "导出文件路径", required = true, paramType = "query")
})
@GetMapping("/file")
public void files(@RequestParam(value = "id", required = true)Long id,@RequestParam(value = "outPath", required = true)String outPath) {
try {
FilePo user = fileDao.findFilePoById(id);
this.zip(outPath, user);
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
public void zip(String zipFileName, FilePo user)
throws Exception {
ByteArrayInputStream byteInputStream= new ByteArrayInputStream(user.getData());
BufferedInputStream inputByte= new BufferedInputStream(byteInputStream);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
zip1(out, inputByte, user.getDescp());
System.out.println("zip done");
out.close();
}
private void zip1(ZipOutputStream out, BufferedInputStream inputByte, String base)
throws Exception {
out.putNextEntry(new ZipEntry(base));
// FileInputStream in = new FileInputStream(f);
int b;
while ((b = inputByte.read()) != -1)
out.write(b);
inputByte.close();
}
}
uploadController.java
package com.example.demo.web;
import com.example.demo.dao.FileDao;
import com.example.demo.dao.po.FilePo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
@RestController
@ApiModel("文件上传")
@RequestMapping(value = "/frontapi/upload")
public class upLoadFileController {
@Autowired
private FileDao fileDao;
@ApiOperation(value = "文件上传", notes = "文件上传")
@ApiImplicitParams({
@ApiImplicitParam(name = "fileId", value = "文件ID", required = true,type = "Integer", paramType = "query"),
@ApiImplicitParam(name = "desc", value = "文件描述", required = true, paramType = "query"),
@ApiImplicitParam(name = "upLoadPath", value = "导出文件路径自己加文件名,改后缀", required = true, paramType = "query")
})
@GetMapping("/file")
public String test(@RequestParam(value = "fileId", required = true)Long fileId,
@RequestParam(value = "desc", required = true)String desc,
@RequestParam(value = "upLoadPath", required = true)String upLoadPath) throws IOException {
File file = new File(upLoadPath);
byte[] bt = this.getFileToByte(file);
FilePo test = new FilePo();
test.setId(fileId);
test.setData(bt);
test.setDescp(desc);
fileDao.save(test);
if (file.exists()) {
file.delete();
}
return "ok";
}
/**
* 文件转为二进制数组
* 等价于fileToBin
*
* @param file
* @return
*/
public byte[] getFileToByte(File file) throws IOException {
byte[] by = new byte[(int) file.length()];
InputStream is = null;
try {
is = new FileInputStream(file);
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
byte[] bb = new byte[2048];
int ch;
ch = is.read(bb);
while (ch != -1) {
bytestream.write(bb, 0, ch);
ch = is.read(bb);
}
by = bytestream.toByteArray();
} catch (Exception ex) {
throw new RuntimeException("transform file into bin Array 出错", ex);
} finally {
is.close();
}
return by;
}
}
FilePo.java
package com.example.demo.dao.po;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Entity
@Table(name="file")
public class FilePo implements Serializable {
@Id
@Column(name="id")
private Long id;
@Column(name="data")
private byte[] data;
@Column(name="descp")
private String descp;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public byte[] getData() {
return data;
}
public void setData(byte[] data) {
this.data = data;
}
public String getDescp() {
return descp;
}
public void setDescp(String descp) {
this.descp = descp;
}
}
FileDao.java
package com.example.demo.dao;
import com.example.demo.dao.po.FilePo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface FileDao extends JpaRepository<FilePo, Long> {
FilePo findFilePoById(long id);
void deleteById(Long id);
}
fileService.java
package com.example.demo.service;
import com.example.demo.dao.po.FilePo;
import com.example.demo.dao.FileDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class fileService {
@Autowired
private FileDao userRepository;
public FilePo findUserById(long id) {
return userRepository.findFilePoById(id);
}
}
DemoApplication.java启动类
注意加上@EnableSwagger2不然,会弹出提示一串英文
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
@ComponentScan(basePackages = {"com.example"})
@EntityScan(basePackages = {"com.example.**.dao.po"})
@EnableJpaRepositories(basePackages = "com.example.**.dao", repositoryFactoryBeanClass = JpaRepositoryFactoryBean.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=true&verifyServerCertificate=false&serverTimezone=GMT%2B8
username: root
password:
driver-class-name: com.mysql.cj.jdbc.Driver
file.sql
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for file
-- ----------------------------
DROP TABLE IF EXISTS `file`;
CREATE TABLE `file` (
`id` bigint(18) NOT NULL COMMENT 'id',
`data` longblob NULL COMMENT '二进制',
`descp` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '描述',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
mvn clean package -Dmaven.test.skip=true打成jar包。jar包外面在写一份application.yml方便修改
启动命令:java –jar spring-boot-file.jar -Dspring.config.location=application.yml
访问地址:http://localhost:8080/swagger-ui.html
下载文件要带文件名,不用转义