Skip to content

Commit 705733e

Browse files
committed
add about file
upload fille spring boot and fastdfs
1 parent d054e75 commit 705733e

File tree

20 files changed

+657
-0
lines changed

20 files changed

+657
-0
lines changed

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.9.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: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
21+
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
22+
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
23+
//-1 means unlimited
24+
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
25+
}
26+
});
27+
return tomcat;
28+
}
29+
30+
}
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: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
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.IOException;
17+
import java.io.InputStream;
18+
19+
@Controller
20+
public class UploadController {
21+
private static Logger logger = LoggerFactory.getLogger(UploadController.class);
22+
@Autowired
23+
private Configurations configuration;
24+
25+
@GetMapping("/")
26+
public String index() {
27+
return "upload";
28+
}
29+
30+
@PostMapping("/upload") //new annotation since 4.3
31+
public String singleFileUpload(@RequestParam("file") MultipartFile file,
32+
RedirectAttributes redirectAttributes) {
33+
if (file.isEmpty()) {
34+
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
35+
return "redirect:uploadStatus";
36+
}
37+
38+
try {
39+
// Get the file and save it somewhere
40+
String path=saveFile(file);
41+
redirectAttributes.addFlashAttribute("message",
42+
"You successfully uploaded '" + file.getOriginalFilename() + "'");
43+
redirectAttributes.addFlashAttribute("path",
44+
"file path url '" + path + "'");
45+
} catch (Exception e) {
46+
logger.error("upload file failed",e);
47+
}
48+
return "redirect:/uploadStatus";
49+
}
50+
51+
@GetMapping("/uploadStatus")
52+
public String uploadStatus() {
53+
return "uploadStatus";
54+
}
55+
56+
/**
57+
* @param multipartFile
58+
* @return
59+
* @throws IOException
60+
*/
61+
public String saveFile(MultipartFile multipartFile) throws IOException {
62+
String[] fileAbsolutePath={};
63+
String fileName=multipartFile.getOriginalFilename();
64+
String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
65+
byte[] file_buff = null;
66+
InputStream inputStream=multipartFile.getInputStream();
67+
if(inputStream!=null){
68+
int len1 = inputStream.available();
69+
file_buff = new byte[len1];
70+
inputStream.read(file_buff);
71+
}
72+
inputStream.close();
73+
FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
74+
try {
75+
fileAbsolutePath = FastDFSClient.upload(file); //upload to fastdfs
76+
} catch (Exception e1) {
77+
e1.printStackTrace();
78+
}
79+
if (fileAbsolutePath==null) {
80+
System.out.println("upload file failed,please upload again!");
81+
}
82+
String path=configuration.getFdfsUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
83+
return path;
84+
}
85+
}
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
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+
public class FastDFSClient {
12+
private static org.slf4j.Logger logger = LoggerFactory.getLogger(FastDFSClient.class);
13+
private static TrackerClient trackerClient;
14+
private static TrackerServer trackerServer;
15+
private static StorageClient storageClient;
16+
private static StorageServer storageServer;
17+
18+
static {
19+
try {
20+
Resource resource = new ClassPathResource("fdfs_client.conf");
21+
File file = resource.getFile();
22+
String configFile = file.getAbsolutePath();
23+
24+
ClientGlobal.init(configFile);
25+
trackerClient = new TrackerClient();
26+
trackerServer = trackerClient.getConnection();
27+
storageServer = trackerClient.getStoreStorage(trackerServer);
28+
} catch (Exception e) {
29+
logger.error("FastDFS Client Init Fail!",e);
30+
}
31+
}
32+
33+
public static String[] upload(FastDFSFile file) {
34+
logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);
35+
36+
NameValuePair[] meta_list = new NameValuePair[1];
37+
meta_list[0] = new NameValuePair("author", file.getAuthor());
38+
39+
long startTime = System.currentTimeMillis();
40+
String[] uploadResults = null;
41+
try {
42+
storageClient = new StorageClient(trackerServer, storageServer);
43+
uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
44+
} catch (IOException e) {
45+
logger.error("IO Exception when uploadind the file:" + file.getName(), e);
46+
} catch (Exception e) {
47+
logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);
48+
}
49+
logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");
50+
51+
if (uploadResults == null) {
52+
logger.error("upload file fail, error code:" + storageClient.getErrorCode());
53+
}
54+
String groupName = uploadResults[0];
55+
String remoteFileName = uploadResults[1];
56+
57+
logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
58+
return uploadResults;
59+
}
60+
61+
public static FileInfo getFile(String groupName, String remoteFileName) {
62+
try {
63+
storageClient = new StorageClient(trackerServer, storageServer);
64+
return storageClient.get_file_info(groupName, remoteFileName);
65+
} catch (IOException e) {
66+
logger.error("IO Exception: Get File from Fast DFS failed", e);
67+
} catch (Exception e) {
68+
logger.error("Non IO Exception: Get File from Fast DFS failed", e);
69+
}
70+
return null;
71+
}
72+
73+
public static InputStream downFile(String groupName, String remoteFileName) {
74+
try {
75+
storageClient = new StorageClient(trackerServer, storageServer);
76+
byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
77+
InputStream ins = new ByteArrayInputStream(fileByte);
78+
return ins;
79+
} catch (IOException e) {
80+
logger.error("IO Exception: Get File from Fast DFS failed", e);
81+
} catch (Exception e) {
82+
logger.error("Non IO Exception: Get File from Fast DFS failed", e);
83+
}
84+
return null;
85+
}
86+
87+
public static void deleteFile(String groupName, String remoteFileName)
88+
throws Exception {
89+
storageClient = new StorageClient(trackerServer, storageServer);
90+
int i = storageClient.delete_file(groupName, remoteFileName);
91+
logger.info("delete file successfully!!!" + i);
92+
}
93+
94+
public static StorageServer[] getStoreStorages(String groupName)
95+
throws IOException {
96+
return trackerClient.getStoreStorages(trackerServer, groupName);
97+
}
98+
99+
public static ServerInfo[] getFetchStorages(String groupName,
100+
String remoteFileName) throws IOException {
101+
return trackerClient.getFetchStorages(trackerServer, groupName, remoteFileName);
102+
}
103+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.neo.fastdfs;
2+
3+
public class FastDFSFile {
4+
private String name;
5+
6+
private byte[] content;
7+
8+
private String ext;
9+
10+
private String md5;
11+
12+
private String author;
13+
14+
public FastDFSFile(String name, byte[] content, String ext, String height,
15+
String width, String author) {
16+
super();
17+
this.name = name;
18+
this.content = content;
19+
this.ext = ext;
20+
this.author = author;
21+
}
22+
23+
public FastDFSFile(String name, byte[] content, String ext) {
24+
super();
25+
this.name = name;
26+
this.content = content;
27+
this.ext = ext;
28+
29+
}
30+
31+
public String getName() {
32+
return name;
33+
}
34+
35+
public void setName(String name) {
36+
this.name = name;
37+
}
38+
39+
public byte[] getContent() {
40+
return content;
41+
}
42+
43+
public void setContent(byte[] content) {
44+
this.content = content;
45+
}
46+
47+
public String getExt() {
48+
return ext;
49+
}
50+
51+
public void setExt(String ext) {
52+
this.ext = ext;
53+
}
54+
55+
public String getMd5() {
56+
return md5;
57+
}
58+
59+
public void setMd5(String md5) {
60+
this.md5 = md5;
61+
}
62+
63+
public String getAuthor() {
64+
return author;
65+
}
66+
67+
public void setAuthor(String author) {
68+
this.author = author;
69+
}
70+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties
2+
#search multipart
3+
spring.http.multipart.max-file-size=10MB
4+
spring.http.multipart.max-request-size=10MB
5+
6+
fastdfs.base.url=http://192.168.53.85:8080/

0 commit comments

Comments
 (0)