Spring Boot 处理文件的上传下载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a2011102394/article/details/80669284

1. 编写测试用例

@RunWith(SpringRunner.class)
@SpringBootTest
public class FileControllerTest {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void whenFileUploadSeccess() throws Exception {
        MockMultipartFile test = new MockMultipartFile("file", "test.txt",
                "multpart/form-date", "hello,world".getBytes());
        mockMvc.perform(MockMvcRequestBuilders.fileUpload("/file")
                .file(test))
                .andExpect(MockMvcResultMatchers.status().isOk());
    }
}

2. 添加fastdfs本地jar包

参考:
https://blog.csdn.net/chs_jdmdr/article/details/7467305

添加依赖如下:

<dependency>
    <groupId>com.crsri</groupId>
    <artifactId>fastdfs</artifactId>
    <version>1.20</version>
    <scope>system</scope>
    <systemPath>${basedir}/src/main/lib/fastdfsClient.jar</systemPath>
</dependency>

或者使用如下中央仓库中的依赖

<dependency>
	<groupId>net.arccode</groupId>
	<artifactId>fastdfs-client-java</artifactId>
	<version>1.27.0</version>
</dependency>

3.创建FastDFS的配置文件

在src/resources目录下创建文件resources/fastdfs/client.conf

connect_timeout = 60
network_timeout = 60
charset = UTF-8
http.tracker_http_port = 80
tracker_server=192.168.25.128:22122

4.封装文件上传的工具类

FastDFSClient

代码如下:

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

/**
 * 〈一句话功能简述〉<br>
 * 〈FastDFS文件上传客户端〉
 * @create 2018/6/12 17:01
 * @since 1.0.0
 */
public class FastDFSClient {

    private TrackerClient trackerClient = null;
    private TrackerServer trackerServer = null;
    private StorageServer storageServer = null;
    private StorageClient1 storageClient = null;

    public FastDFSClient(String conf) throws Exception {
        if (conf.contains("classpath:")) {
            conf = conf.replace("classpath:", this.getClass().getResource("/").getPath());
        }
        ClientGlobal.init(conf);
        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageServer = null;
        storageClient = new StorageClient1(trackerServer, storageServer);
    }

    /**
     * 上传文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     * @param fileName 文件全路径
     * @param extName 文件扩展名,不包含(.)
     * @param metas 文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception {
        String result = storageClient.upload_file1(fileName, extName, metas);
        return result;
    }

    public String uploadFile(String fileName) throws Exception {
        return uploadFile(fileName, null, null);
    }

    public String uploadFile(String fileName, String extName) throws Exception {
        return uploadFile(fileName, extName, null);
    }

    /**
     * 上传文件方法
     * <p>Title: uploadFile</p>
     * <p>Description: </p>
     * @param fileContent 文件的内容,字节数组
     * @param extName 文件扩展名
     * @param metas 文件扩展信息
     * @return
     * @throws Exception
     */
    public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception {

        String result = storageClient.upload_file1(fileContent, extName, metas);
        return result;
    }

    public String uploadFile(byte[] fileContent) throws Exception {
        return uploadFile(fileContent, null, null);
    }

    public String uploadFile(byte[] fileContent, String extName) throws Exception {
        return uploadFile(fileContent, extName, null);
    }
}

FileUtil

代码如下:

import org.springframework.web.multipart.MultipartFile;

/**
 * 〈一句话功能简述〉<br>
 * 〈文件操作工具类〉
 *
 * @create 2018/6/12 17:03
 * @since 1.0.0
 */
public class FileUtil {

    /**
     * 文件上传
     * @param file 要上传的文件
     * @param confPath fastdfs 配置文件的地址
     * @return
     */
    public static String fileUpload(MultipartFile file, String confPath){
        try {
            FastDFSClient fastDFSClient = new FastDFSClient(confPath);
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            return fastDFSClient.uploadFile(file.getBytes(), extName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

5. 文件上传

import com.crsri.secutity.demo.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 〈一句话功能简述〉<br>
 * 〈文件处理的控制器〉
 * @create 2018/6/12 15:37
 * @since 1.0.0
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @PostMapping
    public String upload(MultipartFile file){
        log.info(file.getName());
        log.info(file.getOriginalFilename());
        log.info(String.valueOf(file.getSize()));
        //加载FastDFS的配置文件
        String confPath = "classpath:resources/fastdfs/client.conf";
        String filepath = FileUtil.fileUpload(file, confPath);
        log.info(filepath);
        return filepath;
    }

}

运行测试用例,结果如下

参考资料

https://www.cnblogs.com/ityouknow/p/8298358.html

猜你喜欢

转载自blog.csdn.net/a2011102394/article/details/80669284