Skip to content

Commit ecca616

Browse files
committed
spring-boot-fastDFS
1 parent 03cb1f2 commit ecca616

File tree

13 files changed

+460
-0
lines changed

13 files changed

+460
-0
lines changed
Binary file not shown.

spring-boot-fastDFS/pom.xml

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0"
2+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
4+
http://maven.apache.org/maven-v4_0_0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.neo</groupId>
8+
<artifactId>spring-boot-fastDFS</artifactId>
9+
<packaging>jar</packaging>
10+
<version>1.0</version>
11+
12+
<parent>
13+
<groupId>org.springframework.boot</groupId>
14+
<artifactId>spring-boot-starter-parent</artifactId>
15+
<version>1.5.7.RELEASE</version>
16+
</parent>
17+
18+
<properties>
19+
<java.version>1.8</java.version>
20+
</properties>
21+
22+
<dependencies>
23+
<dependency>
24+
<groupId>org.springframework.boot</groupId>
25+
<artifactId>spring-boot-starter-web</artifactId>
26+
</dependency>
27+
<dependency>
28+
<groupId>org.springframework.boot</groupId>
29+
<artifactId>spring-boot-starter-thymeleaf</artifactId>
30+
</dependency>
31+
<dependency>
32+
<groupId>org.springframework.boot</groupId>
33+
<artifactId>spring-boot-devtools</artifactId>
34+
<optional>true</optional>
35+
</dependency>
36+
<dependency>
37+
<groupId>org.csource</groupId>
38+
<artifactId>fastdfs-client-java</artifactId>
39+
<version>1.27-SNAPSHOT</version>
40+
</dependency>
41+
</dependencies>
42+
43+
<build>
44+
<plugins>
45+
<plugin>
46+
<groupId>org.springframework.boot</groupId>
47+
<artifactId>spring-boot-maven-plugin</artifactId>
48+
</plugin>
49+
</plugins>
50+
</build>
51+
52+
</project>
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.neo;
2+
3+
import org.apache.coyote.http11.AbstractHttp11Protocol;
4+
import org.springframework.boot.SpringApplication;
5+
import org.springframework.boot.autoconfigure.SpringBootApplication;
6+
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
7+
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
8+
import org.springframework.context.annotation.Bean;
9+
10+
@SpringBootApplication
11+
public class FastDFSApplication {
12+
13+
public static void main(String[] args) throws Exception {
14+
SpringApplication.run(FastDFSApplication.class, args);
15+
}
16+
17+
//Tomcat large file upload connection reset
18+
@Bean
19+
public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
20+
21+
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
22+
23+
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
24+
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
25+
//-1 means unlimited
26+
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
27+
}
28+
});
29+
30+
return tomcat;
31+
32+
}
33+
34+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.neo.config;
2+
3+
import org.springframework.beans.factory.annotation.Value;
4+
import org.springframework.stereotype.Component;
5+
6+
@Component
7+
public class Configurations {
8+
9+
@Value("${fastdfs.base.url}")
10+
private String fdfsUrl;
11+
12+
public String getFdfsUrl() {
13+
return fdfsUrl;
14+
}
15+
16+
public void setFdfsUrl(String fdfsUrl) {
17+
this.fdfsUrl = fdfsUrl;
18+
}
19+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.neo.controller;
2+
3+
import org.springframework.web.bind.annotation.ControllerAdvice;
4+
import org.springframework.web.bind.annotation.ExceptionHandler;
5+
import org.springframework.web.multipart.MultipartException;
6+
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
7+
8+
@ControllerAdvice
9+
public class GlobalExceptionHandler {
10+
11+
//https://jira.spring.io/browse/SPR-14651
12+
//4.3.5 supports RedirectAttributes redirectAttributes
13+
@ExceptionHandler(MultipartException.class)
14+
public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
15+
16+
redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
17+
return "redirect:/uploadStatus";
18+
19+
}
20+
}
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package com.neo.controller;
2+
3+
import com.neo.config.Configurations;
4+
import com.neo.fastdfs.FastDFSClient;
5+
import com.neo.fastdfs.FastDFSFile;
6+
import org.slf4j.Logger;
7+
import org.slf4j.LoggerFactory;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.stereotype.Controller;
10+
import org.springframework.web.bind.annotation.GetMapping;
11+
import org.springframework.web.bind.annotation.PostMapping;
12+
import org.springframework.web.bind.annotation.RequestParam;
13+
import org.springframework.web.multipart.MultipartFile;
14+
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
15+
16+
import java.io.FileNotFoundException;
17+
import java.io.IOException;
18+
import java.io.InputStream;
19+
20+
@Controller
21+
public class UploadController {
22+
private static Logger logger = LoggerFactory.getLogger(UploadController.class);
23+
@Autowired
24+
private Configurations configuration;
25+
26+
@GetMapping("/")
27+
public String index() {
28+
return "upload";
29+
}
30+
31+
@PostMapping("/upload") // //new annotation since 4.3
32+
public String singleFileUpload(@RequestParam("file") MultipartFile file,
33+
RedirectAttributes redirectAttributes) {
34+
if (file.isEmpty()) {
35+
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
36+
return "redirect:uploadStatus";
37+
}
38+
39+
try {
40+
// Get the file and save it somewhere
41+
String name=file.getOriginalFilename();
42+
String ext = name.substring(name.lastIndexOf(".") + 1);
43+
String path=saveFile(file,name,ext);
44+
redirectAttributes.addFlashAttribute("message",
45+
"You successfully uploaded '" + file.getOriginalFilename() + "'");
46+
47+
redirectAttributes.addFlashAttribute("path",
48+
"file path url '" + path + "'");
49+
50+
} catch (Exception e) {
51+
logger.error("upload file failed",e);
52+
}
53+
54+
return "redirect:/uploadStatus";
55+
}
56+
57+
@GetMapping("/uploadStatus")
58+
public String uploadStatus() {
59+
return "uploadStatus";
60+
}
61+
62+
63+
64+
public String saveFile(MultipartFile multipartFile, String fileName, String ext){
65+
String path="";
66+
String[] fileAbsolutePath={};
67+
try {
68+
byte[] file_buff = null;
69+
InputStream inputStream=multipartFile.getInputStream();
70+
if(inputStream!=null){
71+
int len1 = inputStream.available();
72+
file_buff = new byte[len1];
73+
inputStream.read(file_buff);
74+
}
75+
inputStream.close();
76+
FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
77+
try {
78+
fileAbsolutePath = FastDFSClient.upload(file); //upload to fastdfs
79+
} catch (Exception e1) {
80+
e1.printStackTrace();
81+
}
82+
if (fileAbsolutePath==null) {
83+
System.out.println("upload file failed,please upload again!");
84+
}
85+
path=configuration.getFdfsUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
86+
} catch (FileNotFoundException e) {
87+
e.printStackTrace();
88+
} catch (IOException e) {
89+
e.printStackTrace();
90+
}
91+
return path;
92+
}
93+
}
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package com.neo.fastdfs;
2+
3+
import org.csource.common.NameValuePair;
4+
import org.csource.fastdfs.*;
5+
import org.slf4j.LoggerFactory;
6+
import org.springframework.core.io.ClassPathResource;
7+
import org.springframework.core.io.Resource;
8+
9+
import java.io.*;
10+
11+
12+
public class FastDFSClient {
13+
private static org.slf4j.Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
14+
private static TrackerClient trackerClient;
15+
private static TrackerServer trackerServer;
16+
private static StorageClient storageClient;
17+
private static StorageServer storageServer;
18+
19+
static {
20+
try {
21+
Resource resource = new ClassPathResource("fdfs_client.conf");
22+
File file = resource.getFile();
23+
String configFile = file.getAbsolutePath();
24+
25+
ClientGlobal.init(configFile);
26+
trackerClient = new TrackerClient();
27+
trackerServer = trackerClient.getConnection();
28+
storageServer = trackerClient.getStoreStorage(trackerServer);
29+
storageClient = new StorageClient(trackerServer, storageServer);
30+
} catch (Exception e) {
31+
e.printStackTrace();
32+
System.out.println("FastDFS Client Init Fail!");
33+
}
34+
}
35+
36+
public static String[] upload(FastDFSFile file) {
37+
logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);
38+
39+
NameValuePair[] meta_list = new NameValuePair[1];
40+
meta_list[0] = new NameValuePair("author", file.getAuthor());
41+
42+
long startTime = System.currentTimeMillis();
43+
String[] uploadResults = null;
44+
try {
45+
uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
46+
} catch (IOException e) {
47+
logger.error("IO Exception when uploadind the file:" + file.getName(), e);
48+
} catch (Exception e) {
49+
logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);
50+
}
51+
logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");
52+
53+
if (uploadResults == null) {
54+
logger.error("upload file fail, error code:" + storageClient.getErrorCode());
55+
}
56+
String groupName = uploadResults[0];
57+
String remoteFileName = uploadResults[1];
58+
59+
logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
60+
System.out.println("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
61+
62+
return uploadResults;
63+
}
64+
65+
public static FileInfo getFile(String groupName, String remoteFileName) {
66+
try {
67+
return storageClient.get_file_info(groupName, remoteFileName);
68+
} catch (IOException e) {
69+
logger.error("IO Exception: Get File from Fast DFS failed", e);
70+
} catch (Exception e) {
71+
logger.error("Non IO Exception: Get File from Fast DFS failed", e);
72+
}
73+
return null;
74+
}
75+
76+
public static InputStream downFile(String groupName, String remoteFileName) {
77+
try {
78+
byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
79+
InputStream ins = new ByteArrayInputStream(fileByte);
80+
return ins;
81+
} catch (IOException e) {
82+
logger.error("IO Exception: Get File from Fast DFS failed", e);
83+
} catch (Exception e) {
84+
logger.error("Non IO Exception: Get File from Fast DFS failed", e);
85+
}
86+
return null;
87+
}
88+
89+
public static void deleteFile(String groupName, String remoteFileName)
90+
throws Exception {
91+
int i = storageClient.delete_file(groupName, remoteFileName);
92+
System.out.println("delete file successfully!!!" + i);
93+
}
94+
95+
public static StorageServer[] getStoreStorages(String groupName)
96+
throws IOException {
97+
return trackerClient.getStoreStorages(trackerServer, groupName);
98+
}
99+
100+
public static ServerInfo[] getFetchStorages(String groupName,
101+
String remoteFileName) throws IOException {
102+
return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
103+
}
104+
}

0 commit comments

Comments
 (0)