新建项目,引入依赖
<repositories>
<repository>
<id>sn</id>
<name>sn</name>
<url>http://oss.sonatype.org/content/repositories/releases</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.luhuiguo</groupId>
<artifactId>fastdfs-spring-boot-starter</artifactId>
<version>0.2.0</version>
</dependency>
</dependencies>
resources文件:application.yml
server:
port: 8899
fdfs:
connect-timeout: 10000 #连接时间
so-timeout: 3000 #响应时间
tracker-list:
- 192.168.88.132:22122
spring:
datasource:
url: jdbc:mysql://localhost/my_mysql
password: 789456123
driver-class-name: com.mysql.jdbc.Driver
username: tan_tan
http:
multipart:
max-file-size: 10MB
编写代码
@RestController
public class UploadController {
@Autowired
private FastFileStorageClient storageClient;
@Autowired
JdbcTemplate jdbcTemplate;
@PostMapping("/uploadFile")
public String upload(@RequestParam("myfile") MultipartFile myfile) throws IOException {
String fileName=FilenameUtils.getExtension(myfile.getOriginalFilename());
StorePath sp= storageClient.uploadFile("group1",myfile.getInputStream(),myfile.getSize(),fileName);
String sql="insert into file(fileName,groupName,filePath) values(?,?,?)";
jdbcTemplate.update(sql,myfile.getOriginalFilename(),sp.getGroup(),sp.getPath());
return sp.getFullPath();
}
@GetMapping("/fileDown/{id}")
public void down(@PathVariable String id, HttpServletResponse response) throws IOException {
List list=jdbcTemplate.query("select * from file where id="+id, new ColumnMapRowMapper());
Map map=(Map)list.get(0);
String fileName= URLEncoder.encode(map.get("fileName").toString(),"UTF-8");
String groupName=map.get("groupName").toString();
String pathName=map.get("filePath").toString();
//告诉浏览器 下载的文件名
response.setHeader("Content-Disposition","attachment; filename="+fileName+"");
//将文件输出到浏览器 fastdfs
byte [] by=storageClient.downloadFile(groupName,pathName);
response.getOutputStream().write(by);
}
}
main方法
@SpringBootApplication
public class BootMain {
public static void main(String[] args) {
SpringApplication.run(BootMain.class);
}
}
上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="uploadFile">
文件:<input type="file" name="myfile"></input>
<input type="submit" value="上传"></input>
</form>
</body>
</html>
下载
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="fileDown/3">下载</a>
</body>
</html>