springboot+fastfdfs+thymeleaf上传图片到远程服务器并显示

先显示效图
在这里插入图片描述
话不多说直接上类
pom.xml

<!--      fastdfs的依赖包-->
   <dependency>
            <groupId>org.csource</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27-RELEASE</version>
        </dependency>
<!--      thymeleaf的依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

fastdfs-client-java依赖包(需要手动导入)
链接: https://pan.baidu.com/s/1H66xNkw7pF_4F4h74Bn66Q 提取码: vash
util类创建FastDFSUtil

package com.sjzew.allySystem.util.fastdfs;

import org.csource.fastdfs.*;
import org.springframework.stereotype.Component;

@Component
public class FastDFSUtil {

    private static TrackerServer ts;
    private static StorageServer ss;

    //加载配置信息(加一次)
    static {
        try {
            ClientGlobal.init("fdfs_client.properties");
            TrackerGroup tg = new TrackerGroup(ClientGlobal.getG_tracker_group().tracker_servers);
            //上传客户端
            TrackerClient tc = new TrackerClient(tg);
            //得到tracker服务器
            ts = tc.getConnection();
            if (ts == null) {
                throw new Exception("没有连接到fastdfs追踪服务器");
            }

            //存储服务器
            ss = tc.getStoreStorage(ts);
            if (ss == null) {
                throw new Exception("没有连接到fastdfs存储服务器");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到fastdfs客户端
     *
     * @return
     */
    public static StorageClient1 getStorageClient() {
        return new StorageClient1(ts, ss);
    }

}

连接服务器的properties
fdfs_client.properties

connect_timeout = 2
network_timeout = 30
charset = UTF-8
http.tracker_http_port = 9999
http.anti_steal_token = no
http.secret_key = 123456

tracker_server = 服务器ip:22122

资源路径映射
Comconfig包下创建
MyWebMvcConfigurer

package com.sjzew.allySystem.config;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/*
    资源路径映射
 */
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images").addResourceLocations("D" +
                ":/images/");
    }
}

Controller类
创建FileController
可以直接返回json提示字符串

package com.sjzew.allySystem.controller.test;

import com.sjzew.allySystem.util.fastdfs.FastDFSUtil;
import com.sjzew.allySystem.util.jsonVo.Json;
import org.csource.common.MyException;
import org.csource.fastdfs.StorageClient1;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/*
文件上传
 */
@Controller
public class FileController {
    @GetMapping(value = "/files")
   public  String file(){

        return "file";
   }
  @PostMapping(value = "/fileUpload")
    @ResponseBody
    public Json fileUpload(@RequestParam(value = "file")MultipartFile file,
                             Model model){
        if(file.isEmpty()){
            System.out.println("文件为空!");
        }
        String fileName=file.getOriginalFilename();//文件名
        String suffixName=fileName.substring(fileName.lastIndexOf("."));//后缀名
        String filePath="D:/images/";//文件上传后路径
        fileName= UUID.randomUUID()+suffixName;//得到新文件名
        File dest=new File(filePath+fileName);//存放的路径+文件名字
        if(!dest.getParentFile().exists()){
            dest.mkdirs();//不存在就创建一个文件
        }

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //上传到服务器
        if(suffixName.equalsIgnoreCase(".png")||suffixName.equalsIgnoreCase(
                ".jpg")){
            StorageClient1 src= FastDFSUtil.getStorageClient();//链接服务器
            try {
                String imgsrc=src.upload_file1(filePath+fileName,"png",null);
                imgsrc="http://114.67.72.214:81/"+imgsrc;
                System.out.println(imgsrc);
                return Json.success(imgsrc);

            } catch (IOException e) {
                e.printStackTrace();
            } catch (MyException e) {
                e.printStackTrace();
            }
        }


        return Json.failed(404,"上传失败!");
    }


}

也可以直接返回url地址到html页面

package com.sjzew.allySystem.controller.test;

import com.sjzew.allySystem.util.fastdfs.FastDFSUtil;
import com.sjzew.allySystem.util.jsonVo.Json;
import org.csource.common.MyException;
import org.csource.fastdfs.StorageClient1;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/*
文件上传
 */
@Controller
public class FileController {
    @GetMapping(value = "/files")
   public  String file(){

        return "file";
   }
   @PostMapping(value = "/fileUpload")
//   @ResponseBody
    public String fileUpload(@RequestParam(value = "file")MultipartFile file,
                        Model model){
        if(file.isEmpty()){
            System.out.println("文件为空!");
        }
        String fileName=file.getOriginalFilename();//文件名
       String suffixName=fileName.substring(fileName.lastIndexOf("."));//后缀名
       String filePath="D:/images/";//文件上传后路径
      fileName= UUID.randomUUID()+suffixName;//得到新文件名
       File dest=new File(filePath+fileName);//存放的路径+文件名字
       if(!dest.getParentFile().exists()){
            dest.mkdirs();//不存在就创建一个文件
       }

       try {
           file.transferTo(dest);
       } catch (IOException e) {
           e.printStackTrace();
       }
       //上传到服务器
       if(suffixName.equalsIgnoreCase(".png")||suffixName.equalsIgnoreCase(
               ".jpg")){
           StorageClient1 src= FastDFSUtil.getStorageClient();//链接服务器
           try {
               String imgsrc=src.upload_file1(filePath+fileName,"png",null);
                imgsrc="http://114.67.72.214:81/"+imgsrc;
               System.out.println(imgsrc);
               model.addAttribute("filename",imgsrc);
               return "file";
           } catch (IOException e) {
               e.printStackTrace();
           } catch (MyException e) {
               e.printStackTrace();
           }
       }

       model.addAttribute("filename","上传失败!");
        return "file";
   }




}

html
tamplates包下创建
file.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/fileUpload" method="post" enctype="multipart/form-data">
    <label>上传图片</label>
    <input th:type="file" name="file"/>
    <input th:type="submit" value="上传"/>
</form>
<p>图片:</p>
<img th:src="@{${filename }}"/>

</body>
</html>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值