1.pom.xml 导入jar
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.luhuiguo/fastdfs-client -->
<dependency>
<groupId>com.luhuiguo</groupId>
<artifactId>fastdfs-client</artifactId>
<version>0.4.0</version>
</dependency>
</dependencies>
启动类
@RestController
public class UploadController {
static FastFileStorageClient storageClient;
static {
FdfsConnectionPool pool = new FdfsConnectionPool();
List<String> trackers = new ArrayList<String>();
trackers.add("192.168.1.135:22122");
//连接到tracker
TrackerConnectionManager tcm = new TrackerConnectionManager(pool, trackers);
TrackerClient trackerClient = new DefaultTrackerClient(tcm);
ConnectionManager cm = new ConnectionManager(pool);
storageClient = new DefaultFastFileStorageClient(trackerClient, cm);
}
@RequestMapping("/upload")
public String uploadfile(@RequestParam MultipartFile myfile) throws IOException {
InputStream is=myfile.getInputStream();
StorePath returnpath=storageClient.uploadFile("group1", is, is.available(),"txt");
return returnpath.getFullPath();
}
@RequestMapping("/download")
public void fdownload(String path,HttpServletResponse response) throws IOException {
byte[] result=storageClient.downloadFile("group1", path);
response.setHeader("Content-Disposition", "attachment;filename="+path);
response.getOutputStream().write(result);
response.getOutputStream().close();
}
public void upload() throws FileNotFoundException {
String path="c:a1.txt";
File file=new java.io.File(path);
FileInputStream fis= new FileInputStream(file);
StorePath returnpath=storageClient.uploadFile("group1", fis, file.length(),"txt");
System.out.println(returnpath);
}
public static void download() throws IOException {
byte[] downloadFile=storageClient.downloadFile("group1", "M00/00/00/wKgBh1tsAl6AYpkFAAAASNo5v_Y382.txt");
FileOutputStream fileout=new FileOutputStream("C:/b_1.txt");
fileout.write(downloadFile);
fileout.close();
}
public static void main(String[] args) throws Exception {
download();
}
@SpringBootApplication
public class FastDfsMain {
public static void main(String[] args) {
SpringApplication.run(FastDfsMain.class, args);
}
}
html页面上传
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit" value="上传">
<a href="/download?path=M00/00/00/wKgBh1tsNzGAV8UWAAABJW9620Q662.txt">下载</a>
</form>
</body>
</html>