springboot +fastdfs 上传文件到到云服务器

时间:2021-05-08 13:14:53

fastdfs在云服务器的搭建和配置:https://blog.csdn.net/qq_41592652/article/details/104006289

springboot结构如下:

springboot +fastdfs 上传文件到到云服务器

application.properties配置如下:

server.port=
#单个文件最大尺寸(设置100)
spring.servlet.multipart.max-file-size=100MB
#一个请求文件的最大尺寸
spring.servlet.multipart.max-request-size=100MB
#设置一个文件上传的临时文件目录
spring.servlet.multipart.location=/root/temp
#读取inputsream阻塞时间
fdfs.connect-timeout=
fdfs.so-timeout=
#tracker地址
fdfs.trackerList=106.12.120.191:
#缩略图配置
fdfs.thumbImage.height=
fdfs.thumbImage.width=
spring.jmx.enabled=false
#通过nginx 访问地址
fdfs.resHost=106.12.120.191
#storage对应的端口
fdfs.storagePort=
#获取连接池最大数量
fdfs.pool.max-total=

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2..BUILD-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.whizen</groupId>
<artifactId>file</artifactId>
<version>0.0.-SNAPSHOT</version>
<name>file</name>
<description>Demo project for Spring Boot</description>
<packaging>war</packaging> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.</version>
</dependency>
<dependency>
<groupId>com.github.tobato</groupId>
<artifactId>fastdfs-client</artifactId>
<version>1.26.-RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<finalName>root</finalName>
</build>
</project>

FdfsConfig类如下:

package com.whizen.file.configure;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; /**
* FdfsConfig主要用以连接fastdfs,FdfsConfiguration使配置生效
*/
@Component
public class FdfsConfig {
@Value("${fdfs.resHost}")
private String resHost; @Value("${fdfs.storagePort}")
private String storagePort; public String getResHost() {
return resHost;
} public void setResHost(String resHost) {
this.resHost = resHost;
} public String getStoragePort() {
return storagePort;
} public void setStoragePort(String storagePort) {
this.storagePort = storagePort;
} }

FdfsConfiguration类如下:

package com.whizen.file.configure;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy; @Configuration
@EnableMBeanExport(registration= RegistrationPolicy.IGNORE_EXISTING)
public class FdfsConfiguration { }

ComonFileUtil类如下:

package com.whizen.file.configure;

import com.github.tobato.fastdfs.domain.MateData;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; import java.io.*;
import java.nio.charset.Charset;
import java.util.Set; @Component
public class CommonFileUtil { private final Logger logger = LoggerFactory.getLogger(FdfsConfig.class); @Autowired
private FastFileStorageClient storageClient; /**
* MultipartFile类型的文件上传ַ
* @param file
* @return
* @throws IOException
*/
public String uploadFile(MultipartFile file) throws IOException {
StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
FilenameUtils.getExtension(file.getOriginalFilename()), null);
return getResAccessUrl(storePath);
} /**
* 普通的文件上传
*
* @param file
* @return
* @throws IOException
*/
public String uploadFile(File file) throws IOException {
FileInputStream inputStream = new FileInputStream(file);
StorePath path = storageClient.uploadFile(inputStream, file.length(),
FilenameUtils.getExtension(file.getName()), null);
return getResAccessUrl(path);
} /**
* 带输入流形式的文件上传
*
* @param is
* @param size
* @param fileName
* @return
*/
public String uploadFileStream(InputStream is, long size, String fileName) {
StorePath path = storageClient.uploadFile(is, size, fileName, null);
return getResAccessUrl(path);
} /**
* 将一段文本文件写到fastdfs的服务器上
*
* @param content
* @param fileExtension
* @return
*/
public String uploadFile(String content, String fileExtension) {
byte[] buff = content.getBytes(Charset.forName("UTF-8"));
ByteArrayInputStream stream = new ByteArrayInputStream(buff);
StorePath path = storageClient.uploadFile(stream, buff.length, fileExtension, null);
return getResAccessUrl(path);
} /**
* 返回文件上传成功后的地址名称ַ
* @param storePath
* @return
*/
private String getResAccessUrl(StorePath storePath) {
String fileUrl = storePath.getFullPath();
return fileUrl;
} /**
* 删除文件
* @param fileUrl
*/
public void deleteFile(String fileUrl) {
if (StringUtils.isEmpty(fileUrl)) {
return;
}
try {
StorePath storePath = StorePath.praseFromUrl(fileUrl);
storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
} catch (FdfsUnsupportStorePathException e) {
logger.warn(e.getMessage());
}
} public String upfileImage(InputStream is, long size, String fileExtName, Set<MateData> metaData) {
StorePath path = storageClient.uploadImageAndCrtThumbImage(is, size, fileExtName, metaData);
return getResAccessUrl(path);
} }

fileControll控制类如下:

package com.whizen.file.controller;

import com.whizen.file.configure.CommonFileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import java.io.IOException; @Controller
public class fileControll {
private final static Logger logger = LoggerFactory.getLogger(fileControll.class); @Autowired
private CommonFileUtil fileUtil;
@CrossOrigin
@ResponseBody
@RequestMapping("/fileup")
public String uoloadFileToFast(@RequestParam("file") MultipartFile file) throws IOException { if(file.isEmpty()){
System.out.println("文件不存在");
}
String path = fileUtil.uploadFile(file);
System.out.println(path);
return "success";
}
}

启动类配置:

package com.whizen.file;

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Import; @SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@Import(FdfsClientConfig.class)
public class FileApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(FileApplication.class);
} public static void main(String[] args) {
SpringApplication.run(FileApplication.class, args);
} }

然后发布到服务器:

ok。