SpringBoot 整合 vsftp(图片服务器) 进行图片储存_JazzyChen的博客-程序员秘密

技术标签: vsftp  springboot  

上一篇已经写了  如何搭建vsftp 进行文件储存(https://blog.csdn.net/weixin_42006112/article/details/102314452),这次主要写的是后台实现图片存储,由于使用起来非常简单,我就直接直接贴代码。

相对详细的链接:https://www.jianshu.com/p/67fc9148f95a

首先添加依赖pom.xml

        <!--图片上传 vsftp-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>

配置文件:application.yml

spring:
#配置文件上传器
  http:
    multipart:
      max-file-size: 100Mb
      max-request-size: 100Mb
  #视图解析器
  mvc:
    view:
      prefix: /pages/
      suffix: .html
  #访问html
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML5

#ftp相关配置
FTP:
  ADDRESS: 192.168.*.*
  PORT: 21
  USERNAME: ftpuser
  PASSWORD: *******
  BASEPATHPIC: /home/ftpuser/images
  BASEPATHFILE: /home/ftpuser/file
#图片服务器相关配置
IMAGE:
  BASE:
    URL: http://192.168.117.130/images
#文件地址
FILE:
  BASE:
    URL: http://192.168.117.130/file

或者是:application.properties

#配置数据库连接信息
spring.datasource.url=jdbc:mysql:///db_demo?useUnicode=true&characterEncoding=utf8
spring.datasource.username=#
spring.datasource.password=#
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#Mybatis扫描接口对应的xml文件
mybatis.mapper-locations=classpath:mappers/*.xml
#起别名。可省略写mybatis的xml中的resultType的全路径  
mybatis.type-aliases-package=com.zhu.pojo
#配置文件上传器
spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=100Mb
#ftp相关配置
FTP.ADDRESS=192.168.xx.xxx
FTP.PORT=21
FTP.USERNAME=ftpuser
FTP.PASSWORD=*******
FTP.BASEPATH=/home/ftpuser/images
FTP.BASEPATHFILE=/home/ftpuser/file
#图片服务器相关配置
IMAGE.BASE.URL=http://192.168.xx.xxx/images
FILE.BASE.URL=http://192.168.xx.xxx/file
#视图解析器
spring.mvc.view.prefix=/pages/
spring.mvc.view.suffix=.html

然后就是图片上传工具,直接复制即可使用 FtpFileUtil 

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class FtpFileUtil {

    @Value("${FTP.ADDRESS}")
    private String host;
    // 端口
    @Value("${FTP.PORT}")
    private int port;
    // ftp用户名
    @Value("${FTP.USERNAME}")
    private String userName;
    // ftp用户密码
    @Value("${FTP.PASSWORD}")
    private String passWord;

    /**
     * Description: 向FTP服务器上传文件
     *
     *host     FTP服务器ip
     *port     FTP服务器端口
     *username FTP登录账号
     *password FTP登录密码
     *basePath FTP服务器基础目录,/home/ftpuser/images
     * @param filePath FTP服务器文件存放路径。例如分日期存放:/2018/05/28。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名
     * @param input    输入流
     * @return 成功返回true,否则返回false
     */
    public boolean uploadFile(String filePath, String filename,String basePath, 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.enterLocalPassiveMode();
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            //上传文件
            if (!ftp.storeFile(filename, 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;
    }
}

随机数生成:IDUtils,为的是防止名字相同导致覆盖

import java.util.Random;

public class IDUtils {
    public static String getImageName() {
        //取当前时间的长整形值包含毫秒
        long millis = System.currentTimeMillis();
        //long millis = System.nanoTime();
        //加上三位随机数
        Random random = new Random();
        int end3 = random.nextInt(999);
        //如果不足三位前面补0
        String str = millis + String.format("%03d", end3);

        return str;
    }
}

上传图片案例

import com.jazzychen.myspringboot.util.FtpFileUtil;
import com.jazzychen.myspringboot.util.IDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@ResponseBody
@RequestMapping("/pic")
public class UserContrller {

    // 文件在服务器端保存的主目录
    @Value("${FTP.BASEPATHPIC}")
    private String basePath;
    // 访问图片时的基础url
    @Value("${IMAGE.BASE.URL}")
    private String baseUrl;

    @Autowired
    private FtpFileUtil ftpFileUtil;

    @PostMapping("/upload")
    public void picUpload(@RequestParam("pic")MultipartFile uploadFile){
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd");
            //获取图片名字
            String oldName = uploadFile.getOriginalFilename();
            //创建新的名字
            String newName = IDUtils.getImageName();
            newName = newName + oldName.substring(oldName.lastIndexOf("."));
            //生成文件在服务器端存储的子目录
            String filePath = simpleDateFormat.format(new Date());
            //把图片上传到服务器
            //转io流
            InputStream inputStream = uploadFile.getInputStream();

            boolean result = ftpFileUtil.uploadFile(filePath, newName,basePath, inputStream);
            if (result){
                System.out.println("图片地址"+ baseUrl + filePath + "/" + newName);
            }else {
                System.out.println("false");
            }
        }catch (Exception e){
            System.out.println(e);
        }
    }

前端代码: index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

  <form action="/pic/import" enctype="multipart/form-data" method="post">
       <input type="text" name="username"><br>
       <input type="password" name="password"><br>
       <input type="file" name="pic"><br>
       <input type="submit" value="提交">
   </form>

</body>
</html>

追后附上结构图与效果图

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42006112/article/details/102390705

智能推荐

Froont!在线可视化响应式网页设计工具_Hustudent20080101的博客-程序员秘密

Home  /  热门下载 /神器下载   /  正文更多44今天要推荐的神器来自http://froont.com/ ,猜猜它有神马强悍的功能呢?是滴,进入网站后,你就会看到他说:“原来还可以在浏览器里设计网页,仅仅只需要拖放即可!”Froont是一个允许设计师在线设计响应式网页的工具,不需要程序员介入的设计编程工具,为设计师们提供了可视化

docker安装jenkins+gitlab_docker gitlab jenkins_coke-520的博客-程序员秘密

一、安装jenkinsdocker search jenkins可以搜索docker官方仓库的镜像然后从docker仓库中下载镜像docker pull jenkinsci/blueocean创建jenkins工作挂载目录mkdir /var/jenkins_home -pchown -R 1000:1000 /var/jenkins_home执行如下命令创建启动jenkins容器docker run -d --name jenkins -p 8080:8080 -p

verdi显示数组设置_verdi 看数组_落雨无风的博客-程序员秘密

IC设计中verdi显示数组设置默认情况下,verdi是显示数组的。默写特殊情况下,verdi不会显示数组信号的值具体设置如下:![verdi数组设置](https://img-blog.csdnimg.cn/dab4574bd64447a4b47109dc5a42e3b3.png#pic_center)4行是生成fsdb波形;5行是生成包含几层波形文件;6行是显示之前不能显示的数组信号...

华为交换机基于IP地址划分VLAN配置实验_华为交换机基于ip划分vlan_Ang.sut倾城♛ ♛的博客-程序员秘密

一、实验拓扑图: 二、实验要求:如图所示,查看S1、S2和S3的配置。1.测试同一网段的PC和服务器能否通信?(仅30的网段可以,WHY?)2.思考S1交换机发送给S3交换机时的上行流量是否均有TAG标签?3.假设S1交换机由于某种原因,无法配置,请在S3的E4端口进行相应配置,根据相应IP进行VLAN的划分。4.测试同一网段的PC和服务器能否通信?(YES)。三、配置命令与原因分析:1.测试同一网段的PC和服务器能否...

html开发时使用js封装Vue组件(二)_html+css+js封装为组件_爱学习的ljz的博客-程序员秘密

需求最近项目组里有个项目想使用vue开发,但是不想搭建环境,因此就采用引入js的方式来进行开发,然后有很多页面需要用到一些公共的部分,因此想让我开发一些公共组件,使用Vue注册组件都是在webpack管理的项目下进行 的封装组件,因此对无node搭建环境的情况下不太了解如何封装公共组件。在重新阅读了Vue官网的组件注册之后,产生了一个想法,可以在js中注册好Vue的全局组件,然后哪个页面需要用到该组件就引用该js文件,将组件内dom模板的定义也写在了js文件中。一开始就通过这样的方式注册了很多公共组件

随便推点

BZOJ 1597: [Usaco2008 Mar]土地购买【斜率优化】_Sdywolf的博客-程序员秘密

Description农夫John准备扩大他的农场,他正在考虑N (1 <= N <= 50,000) 块长方形的土地. 每块土地的长宽满足(1 <= 宽 <= 1,000,000; 1 <= 长 <= 1,000,000). 每块土地的价格是它的面积,但FJ可以同时购买多快土地. 这些土地的价格是它们最大的长乘以它们最大的宽, 但是土地的长宽不能交换. 如果FJ买一块3x5的地和一块5x3的地,则

七周七并发之线程与锁_weixin_34007291的博客-程序员秘密

2019独角兽企业重金招聘Python工程师标准&gt;&gt;&gt; ...

SpringBoot项目使用Junit单元测试案例_spring boot生成单元测试用例_拄杖忙学轻声码的博客-程序员秘密

2、@SpringBootTest(classes = {Application.class}) 指定启动类,如果不配置启动类,则执行的包、类可以放在该项目的任何地方。如果指定了启动类,那么启动类执行的类、包必须也放在 test 目录相应的包下,否则会报错。4、@Before:在 @Test 执行之前执行。5、@After:在 @Test 执行之后执行。3、@Test:测试执行的主方法。

FreeMarker常用语法学习_freemarker sort_by_xiaocha2008的博客-程序员秘密

最近在搞一个:静态化的新闻发布系统,使用的是SpringMVC+FreeMarker来进行生产整个网站。把FreeMarker的一些常用语法贴出来。。。。1.API网址http://freemarker.sourceforge.net/docs/2.一个Table的例子freemarker 对表格的控制这里将所有需要在一个区域显示到数据全部add到一个叫做zbj的list中了

微服务迁移记(五):WEB层搭建(2)-SpringSecurity集成_程序员周瑜的博客-程序员秘密

一、redis搭建二、WEB层主要依赖包三、FeignClient通用接口以上三项,参考《微服务迁移记(五):WEB层搭建(1)》接下来,集成SpringSecruity,实现用户登录。总体思路为:自定义UserDetails、UserDetailsService,重载WebSecurityConfigurerAdapter实现自定义表单登录,将菜单和按钮权限也扔到SpringSecr...

第十二讲 m-序列的伪随机性_Forward南的博客-程序员秘密

1 序列的伪随机性回顾随机序列的一般特性Golomb伪随机公设伪随机序列的定义2 m-序列的伪随机性m序列的随机性

推荐文章

热门文章

相关标签