springboot图片上传下载实例详解

1、访问本地路径获取图片url,适用于前端上传文件保存到服务器
通过映射可以直接获取图片,应用在前端上传的图片比如都保存在D:/OTA路径下,下次再获取的时候就可以用这种方法得到一个url为 http://127.0.0.1:10002/OTA/xxx.jpg

@Configuration
public class MyConfiguration extends WebMvcConfigurerAdapter {

//    @Override
//    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        /**
//         * @Description: 对文件的路径进行配置, 创建一个虚拟路径/templates/** ,即只要在<img src="/templates/picName.jpg" />便可以直接引用图片
//         *这是图片的物理路径  "file:/+本地图片的地址"
//         */
//        registry.addResourceHandler("/templates/**").addResourceLocations
//                ("file:/E:/IdeaProjects/gaygserver/src/main/resources/static/");
////        registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/static/");
//        super.addResourceHandlers(registry);
//    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //和页面有关的静态目录都放在项目的static目录下
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        //上传的图片在D盘下的OTA目录下,访问路径如:http://localhost:8081/OTA/d3cf0281-bb7f-40e0-ab77-406db95ccf2c.jpg
        //其中OTA表示访问的前缀。"file:D:/OTA/"是文件真实的存储路径
        registry.addResourceHandler("/OTA/**").addResourceLocations("file:D:/OTA/");
    }
}

2、通过接口从ftp服务器获取图片并缓存,接口其实就是一个url(ftp服务器需要登录)
control层中接口,其中response.setHeader("Cache-Control", "max-age=604800");是设置缓存,如果获取多张图片后点击第二第三张图片就不需要再请求这个接口了,因为浏览器已经自动缓存下来。

@RequestMapping(value = "/image", method = RequestMethod.GET)
    public void imageDisplay(@RequestParam String fileId, HttpServletResponse response) {
        Attachment attachment = attachmentMapper.selectByPrimaryKey(fileId);

        String host = ftpConfig.getFtpHost();
        int port = ftpConfig.getFtpPort();
        String userName = ftpConfig.getFtpUserName();
        String password = ftpConfig.getFtpPassWord();
        String remotePath = attachment.getFilePath();
        String fileName = attachment.getFileName();

        try {
            response.setContentType("image/jpeg");  //设置显示图片
            response.setHeader("Cache-Control", "max-age=604800"); //设置缓存
            FtpUtil.downloadFile(host, port, userName, password, remotePath, fileName, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

配置文件applicati.yml中关于ftp服务器的相关配置

pathconfig:
  ftpHost: 172.16.11.66
  ftpPort: 21
  ftpUserName: sys
  ftpPassWord: SYS!!@@
  ftpOperativePath: YY
  ftpCloudPath: QYY
  ftpPortalPath: MH
  ftpMobilePath: MOBILE
  ftpPropertyPath: WY

将ftp服务器的相关配置变成类FtpConfig

@Component
@ConfigurationProperties(prefix = "pathconfig")
@EnableConfigurationProperties({FtpConfig.class})
public class FtpConfig {
    private String ftpHost;
    private int ftpPort;
    private String ftpUserName;
    private String ftpPassWord;
    private String ftpOperativePath;
    private String ftpCloudPath;
    private String ftpPortalPath;
    private String ftpMobilePath;
    private String ftpPropertyPath;

    setter和getter方法...
}

延生:既然有显示图片接口,那么就有下载图片接口

@RequestMapping(value = "", method = RequestMethod.GET)
    public void fileDownload(@RequestParam String fileId, HttpServletResponse response) {
        Attachment attachment = attachmentMapper.selectByPrimaryKey(fileId);

        if (null != attachment) {
            String host = ftpConfig.getFtpHost();
            int port = ftpConfig.getFtpPort();
            String userName = ftpConfig.getFtpUserName();
            String password = ftpConfig.getFtpPassWord();
            String remotePath = attachment.getFilePath();
            String fileName = attachment.getFileName();
            String oFileName = attachment.getoFileName();

            try {
                response.setContentType("application/octet-stream"); //设置图片下载
                response.setHeader("Cache-Control", "max-age=604800");//设置缓存
                response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" +
                        URLEncoder.encode(oFileName, "UTF-8"));//设置文件名
                FtpUtil.downloadFile(host, port, userName, password, remotePath, fileName, response.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

FtpUtil

public class FtpUtil {

    /**
     * Description: 向FTP服务器上传文件
     *
     * @param host     FTP服务器hostname
     * @param port     FTP服务器端口
     * @param username FTP登录账号
     * @param password FTP登录密码
     * @param basePath FTP服务器基础目录
     * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名
     * @param input    输入流
     * @return 成功返回true,否则返回false
     */
    public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                                     String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPClient ftp = new FTPClient();

        try {
            int reply;

            ftp.connect(host, port);// 连接FTP服务器
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            //切换到上传目录
            if (!ftp.changeWorkingDirectory(basePath + filePath)) {
                //如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            //上传文件
            if (!ftp.storeFile(new String(filename.getBytes("GBK"), "iso-8859-1"), input)) {
                return result;
            }
            input.close();
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param host       FTP服务器hostname
     * @param port       FTP服务器端口
     * @param username   FTP登录账号
     * @param password   FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName   要下载的文件名
     * @param localPath  下载后保存到本地的路径
     * @return
     */
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                                       String fileName, String localPath) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                String f = new String(ff.getName().getBytes("ISO-8859-1"), "GBK");

                if (f.equals(fileName)) {
                    String[] split = f.split("_");
                    File localFile = new File(localPath + "/" + split[1]);

                    OutputStream is = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }

            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param host       FTP服务器hostname
     * @param port       FTP服务器端口
     * @param username   FTP登录账号
     * @param password   FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName   要下载的文件名
     * @param ops        下载后保存到本地的路径
     * @return
     */
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                                       String fileName, OutputStream ops) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                String f = new String(ff.getName().getBytes("ISO-8859-1"), "GBK");

                if (f.equals(fileName)) {
                    ftp.retrieveFile(ff.getName(), ops);
                    ops.close();
                }
            }

            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

}


作者:想去最最最北
链接:https://www.jianshu.com/p/54e0ca450f88
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/lesouls/article/details/80163674