ftp+spring boot+vue.js图片上传并保存到数据库

  1. 前端使用vue 使用iview 中的upload上传组件

  2. 后端使用spring boot 中的 MultipartFile+ ftp 将图片上传到服务器

  3. pom.xml 导入相应jar包
  • <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>com.google.code.gson</groupId>
                <artifactId>gson</artifactId>
                <version>2.8.5</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.1.9</version>
            </dependency>
    
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.47</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>1.4.0</version>
            </dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-lang3</artifactId>
            </dependency>
            <!--ftp图片上传-->
            <dependency>
                <groupId>commons-net</groupId>
                <artifactId>commons-net</artifactId>
                <version>3.6</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    upload:
      ftpIp: 127.0.0.1  //实际写自己图片服务器IP
      ftpport: 21
      ftpname: ftpuser
      ftppws: ftpuser
      ftppath: /home/ftpuser/imgs
      ftpUrl: http://127.0.0.1:8081/  ##访问路径

     前端代码iview代码

  • <Form-Item label="基地图片" prop="basePhoto">
       <Upload
             ref="upload"
             :show-upload-list="false"
             :on-format-error="handleFormatError"
             :on-exceeded-size="handleMaxSize"
             :on-success="handleSuccess"
             :format="['jpg','jpeg','png']"
             :max-size="2048"
             :before-upload="handleBeforeUpload"
             :data="img_ty" //上传时附带的额外参数(参数必须是对象类型),如没有可以不写
             multiple
             action="/ht/baseUpload">
             <i-button icon="ios-cloud-upload-outline" style="color: #3399ff">上传图片</i-button>
        </Upload>
    </Form-Item>
    img_ty: {
       img_name:'', //数定义额外参
     },
              //上传前的方法
               handleBeforeUpload(file){
                    this.imgShow = false;
                    this.spinShow = true;
                    return this.checkedImgWidthHeight(file,265,150)
                },
              //获取图片宽高,因对图片大小有要求,所以限制上传的图片大小
               checkedImgWidthHeight(file,widt,heigh){
                    let that = this;
                    return new Promise(function (resolve, reject) {
                        let reader = new FileReader;
                        reader.onload = function (evt) {
                            let image = new Image();
                            image.src = evt.target.result;
                            image.onload = function () {
                                let width = this.width;
                                let height = this.height;
                                let flag = width>=widt&&height>=heigh;
                                if(!flag){
                                    that.$Modal.info({
                                        title: '系统提示',
                                        content: '<p style="font-size:16px;">请上传宽高大于等于'+widt+'*'+heigh+'的图片</p>',
                                    });
                                    that.spinShow = false;
                                    reject();
                                }else{
                                    resolve();
                                }
                            };
                            image.onerror = reject;
                            image.src = evt.target.result;
                        };
                        reader.readAsDataURL(file);
                    })
                },
                //上传错误时的方法
                handleFormatError(file){
                    this.$Notice.warning({
                        title: '系统提示',
                        desc: '名为' + file.name + '的文件格式错误'
                    });
                },
                handleMaxSize(file){
                    this.$Notice.warning({
                        title: '系统提示',
                        desc: '名为' + file.name + '的文件过大'
                    });
                },
                handleSuccess(res, file){
                    if(res.result == true){
                        this.basePhoto = res.data;
                        this.imgShow = true;
                        this.$Message.success("图片上传成功")
                    }else{
                        this.imgShow = false;
                        this.$Message.error("图片上传失败")
                    }
                    this.spinShow = false;
                }

     

  • controller代码

  •       /**
         * 
         * @param file
         * @param request
         * @return
         */
        @RequestMapping(value = "/baseUpload", method = RequestMethod.POST)
        @ResponseBody
        public ResultModel upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
            ResultModel result = new ResultModel();
            String imgName = request.getParameter("img_name");
            int width = 265;
            int height = 150;
            try {
                if(!file.isEmpty()){
                    String fileName = file.getOriginalFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf(".") +1);
                    String newName = FileUtil.getFileName(fileName);
                    if(fileUtil.cutImage(file,newName,suffix,width,height)) {
                        if(StringUtils.isNotEmpty(imgName)){
                            fileUtil.deleteFile(FileUtil.getFile(imgName)); //图片更新后删除原图片
                        }
                        result.setData(hrefUrl+newName);  //图访问路径,返回到前端,提及form表单保存时将访问路径保存到数据库
                        result.setResult(true);
                    }else{
                        result.setResult(false);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return result;
        }

    图片上传工具类

  • package com.jq.xinj.agriculture.util;
    
    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;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.*;
    
    /**
     * @author 尚**木
     * @ClassName FileUtile
     * @date 2019/5/29 10:28
     * @Version 1.0
     */
    @Component
    public class FileUtil {
        @Value("${upload.ftpIp}")
        private String FTP_IP;
    
        @Value("${upload.ftpport}")
        private Integer FTP_PORT;
    
        @Value("${upload.ftpname}")
        private String FTP_NAME;
    
        @Value("${upload.ftppws}")
        private String FTP_PWS;
    
        @Value("${upload.ftppath}")
        private String FTP_BASEPATH;
    
        /**
         * 图片裁剪方法 在我的Java图片裁剪博客有详细介绍
         * @param file
         * @param fileName
         * @param suffix
         * @param width
         * @param height
         * @return
         */
        public boolean cutImage(MultipartFile file,String fileName,String suffix, int width,int height){
            int x = 0;
            int y = 0;
            boolean flag = false;
            try {
                BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
                BufferedImage bf = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
                bf.getGraphics().drawImage(bufferedImage,x,y,width,height,null);
                ByteArrayOutputStream baot = new ByteArrayOutputStream();
                ImageIO.write(bf,suffix,baot);
                byte[]  buff =  baot.toByteArray();
                InputStream inputStream =  new ByteArrayInputStream(buff);
                flag = ftpUpload(inputStream,fileName);
            }catch (Exception e){
                e.printStackTrace();
                return false;
            }
            return flag;
        }
    
        /**
         * 图片上传方法
         * @param inputStream
         * @param fileName
         * @return
         */
        public boolean ftpUpload(InputStream inputStream, String fileName){
            boolean flag = false;
            FTPClient ftpClient = new FTPClient();
            ftpClient.setControlEncoding("UTF-8");
            try {
                int reply;
                ftpClient.connect(FTP_IP,FTP_PORT);//服务器地址和端口
    //            ftpClient.enterLocalPassiveMode();
                ftpClient.login(FTP_NAME,FTP_PWS);//登录的用户名和密码
                reply = ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    return flag;
                }
                System.out.println(reply); //ftp不会报错只会返回状态码,可以根据状态码查找错误
                ftpClient.enterLocalPassiveMode();
    
                //设置文件类型
                ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
                //设置上传路径
                ftpClient.changeWorkingDirectory(FTP_BASEPATH);
    
                //读取本地文件,给出的是本地文件地址
    //            InputStream inputStream = file.getInputStream();
                //1.服务器端保存的文件名,fileName
                // 2.上传文件的inputstream
                ftpClient.storeFile(fileName,inputStream);
                inputStream.close();
                flag = true;
            }catch (Exception e){
                e.printStackTrace();
                flag = false;
            }finally {
                try {
                    ftpClient.logout();
                }catch (Exception e){
                    e.printStackTrace();
                }
    
            }
            return flag;
        };
    
        /**
         * 删除服务器上的图片 登陆图片服务器后 到相应的目录下根据图片名称删除图片
         * @param FileName
         * @return
         */
        public boolean deleteFile(String FileName) {
            boolean flag = false;
            FTPClient ftp = new FTPClient();
            ftp.setControlEncoding("UTF-8");
            try {
                int reply;
                ftp.connect(FTP_IP, FTP_PORT);// 连接FTP服务器
                ftp.login(FTP_NAME, FTP_PWS);// 登录
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return flag;
                }
                ftp.enterLocalPassiveMode();
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftp.makeDirectory(FTP_BASEPATH);
                ftp.changeWorkingDirectory(FTP_BASEPATH);
                flag = ftp.deleteFile(FileName);
    //            System.out.println(ftp.getReplyCode()); //250 表示删除成功
    //            System.out.println(flag);  //flag==true 表示成功
                ftp.logout();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return flag;
        }
    
        /**
         * 文件重新命名
         * @param fileName
         * @return
         */
        public static String getFileName(String fileName){
            //获取文件类型
            String type = fileName.substring(fileName.lastIndexOf("."));
            //获取文件名字
    //        String name = fileName.substring(0,fileName.indexOf("."));
            String name = TimeHelper.getCurrentCompactTime();
            return name+type;
        }
    
        /**
         * 获取服务器图片名字
         * @param fileUrl
         * @return
         */
        public static String getFile(String fileUrl){
            String filName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
            return filName;
        }
    }
    

    Java图片裁剪博客https://blog.csdn.net/mumu_126/article/details/91047862

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值