java调用fastdfs

在github.com中查找fastdfs (官方不支持连接池而这个是支持连接池的)

 在pom中加入依赖(由于阿里云中央仓库没有这个依赖需要配置新的私服仓库)

引入私服地址

<repositories>
        <repository>
            <id>sn</id>
            <name>sn</name>
            <url>http://oss.sonatype.org/content/repositories/releases</url>
        </repository>
    </repositories>

添加fastdfs依赖

<dependency>
            <groupId>com.luhuiguo</groupId>
            <artifactId>fastdfs-spring-boot-starter</artifactId>
            <version>0.2.0</version>
        </dependency>

pom配置文件如图

 application.yml配置:

server:
  port: 8899
fdfs:
  #超时时间
  connect-timeout: 1000
  #响应的超时时间
  so-timeout: 3000
  tracker-list:
    - 192.168.63.133:22122
spring:
  datasource:
    url: jdbc:mysql://localhost/factory
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    #上传的文件大小
  http:
    multipart:
      max-file-size: 10485760

上传下载文件html

上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="fupload">
    文件<input type="file" name="myFile">
    <input type="submit" value="上传">
</form>
</body>
</html>

下载

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>下载文件</title>
</head>
<body>
<a href="fdownload/1">下载文件</a>
</body>
</html>

java代码

@RestController
public class UploadConller {
    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * 是从浏览器提交过来
     * @param myFile
     * @return
     */
    @PostMapping("/fupload")
    public String upload(@RequestParam("myFile")MultipartFile myFile) throws IOException {
        String extName = FilenameUtils.getExtension(myFile.getOriginalFilename());
        StorePath sp = storageClient.uploadFile("group1",myFile.getInputStream(),myFile.getSize(),extName);
        String sql="insert into myfiled(filename,groupName,filepath) values(?,?,?)";
        jdbcTemplate.update(sql,myFile.getOriginalFilename(),sp.getGroup(), sp.getPath());
        return sp.getFullPath();
    }
    @GetMapping("/fdownload/{id}")
    public void download(@PathVariable String id, HttpServletResponse response) throws IOException {
        List list=jdbcTemplate.query("select * from myfiled where fileid="+id,new ColumnMapRowMapper());
        Map map = (Map)list.get(0);
        String  fileName = map.get("filename").toString();
        String groupName=map.get("groupName").toString();
        String pathName = map.get("filepath").toString();
        //告诉浏览器下载的文件名
        //通过设置响应头
        response.setHeader("Content-Disposition","attachment; filename="+fileName+"");
        //将文件内容输出到浏览器
        byte[] bt=storageClient.downloadFile(groupName,pathName);
        response.getOutputStream().write(bt);
    }

猜你喜欢

转载自blog.csdn.net/weixin_43788708/article/details/84823849