admin管理员组

文章数量:1558087

前言:

        项目需求:做一个图片服务器,用于存放业务部门做的宣传图片;支持上传、下载和在线查看。

一、需求分解

1. 上传、下载功能比较成熟,相对好实现;

2. 在线预览,需要分为单个文件预览和多个文件预览;

二、接口设计

请求路径描述
POST        /pic/upload上传接口,返回文件预览地址
GET         /pic/download?fileName=文件下载接口
GET        /pic/list文件列表,返回文件预览地址数组
GET        /pic/file/文件单文件预览;资源查找设计,无相关接口设计

三、功能实现

工具列表:

jdk:    1.8.0_291
springboot:    2.3.2.RELEASE
IDEA:    2019.3.5

配置文件:

server:
  port: 8002
  servlet:
    context-path: /pic
spring:
  application:
    name: pic-server
  jackson:
    default-property-inclusion: non_null
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8

pic:
  dir: F:/work/pic/

1. 文件预览

添加资源配置:


@Configuration
public class PicConfig implements WebMvcConfigurer {

    @Value("${pic.dir}")
    private String picDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/file/**")
                .addResourceLocations("file:" + picDir);
    }
}

配置好以后可以启动工程查看图片资源:

本地目录下的资源如下:

PostMan 请求:

2. 文件上传、下载,文件列表

 接口描述:

@Slf4j
@RestController
@RequestMapping()
public class PicController {

    @Autowired
    FileService fileService;

    @PostMapping("/upload")
    public ResultBean upload(@RequestParam("media") MultipartFile file) {
        log.info("save file name {}", file.getOriginalFilename());
        String filePath = fileService.saveFile(file);
        return ResultBean.success(filePath);
    }

    @GetMapping("/download")
    public ResultBean downloadFile(HttpServletResponse response,
                                   @RequestParam(value = "fileName") String fileName) {

        Boolean result = fileService.downloadFile(response, fileName);
        return ResultBean.success(result);
    }

    @GetMapping("/list")
    public ResultBean list() {
        return ResultBean.success(fileService.getFiles());
    }

}

:ResultBean 结构体可参考如果优美地设计 springboot 接口返回_清泉影月-CSDN博客

核心服务:

@Slf4j
@Service
public class FileService {

    @Value("${server.port}")
    private String port;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${pic.dir}")
    private String picDir;


    public String saveFile(MultipartFile multipartFile) {

        String filename = multipartFile.getOriginalFilename();

        File file = new File(picDir + filename);

        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            log.error("save file error,{}", e.getMessage());
            return "";
        }

        return getFileUrl(filename);
    }

    public List<String> getFiles() {
        List<String> fileUrls = new ArrayList<>();

        File file = new File(picDir);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File file1 : files) {
                    fileUrls.add(getFileUrl(file1.getName()));
                }
            }
        }
        return fileUrls;
    }

    private String getFileUrl(String fileName) {
        try {
            InetAddress address = InetAddress.getLocalHost();
            String fileUrl = "http://" + address.getHostAddress() + ":" + port + contextPath + "/file/" + fileName;
            log.info("fileUrl:{}", fileUrl);
            return fileUrl;
        } catch (UnknownHostException e) {
            log.error("get host error,{}", e.getMessage());
            return "";
        }
    }

    public Boolean downloadFile(HttpServletResponse response, String fileName) {
        File file = new File(picDir + fileName);
        if (file.exists()) {
            try {
                FileInputStream fileInputStream = new FileInputStream(file);

                response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
                ServletOutputStream outputStream = response.getOutputStream();

                FileCopyUtils.copy(fileInputStream, outputStream);
                return true;
            } catch (IOException e) {
                log.error("download file error: {}", e.getMessage());
                return false;
            }
        }
        return false;
    }

}

PostMan 测试上传和下载:

上传:

下载(浏览器打开链接会直接下载文件):

四、 结语

        1. 上述是一个开放的存储系统,没有设计权限;

        2. 可以用于存储其它文件,文件预览不保证效果;

        3. 以上引用了某网红的图片,如果涉及侵权,可联系删除。

本文标签: 上传下载服务器图片SpringBoot