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

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

springboot结构如下:

springboot +fastdfs 上传文件到到云服务器_第1张图片

application.properties配置如下:

server.port=8080
#单个文件最大尺寸(设置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=600
fdfs.so-timeout=1500
#tracker地址
fdfs.trackerList=106.12.120.191:22122 
#缩略图配置
fdfs.thumbImage.height=150
fdfs.thumbImage.width=150
spring.jmx.enabled=false
#通过nginx 访问地址
fdfs.resHost=106.12.120.191
#storage对应的端口
fdfs.storagePort=23000
#获取连接池最大数量
fdfs.pool.max-total=200 

 

pom.xml配置如下:

"1.0" encoding="UTF-8"?>
"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">
    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.3.BUILD-SNAPSHOT
         
    
    com.whizen
    file
    0.0.1-SNAPSHOT
    file
    Demo project for Spring Boot
    war


    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            log4j
            log4j
            1.2.17
        
        
            com.github.tobato
            fastdfs-client
            1.26.1-RELEASE
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
        root
    

 

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 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。

 

 

 

你可能感兴趣的:(springboot +fastdfs 上传文件到到云服务器)