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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/mumu_126/article/details/91446255
  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

展开阅读全文

文件读取并保存数据库的问题

08-21

下面OnButton1()函数是读取文件并保存到数据库的一个image类型的字段,rnOnButton2函数是从数据库中把数据取出写入文件:rn文件1.txt的内容如下:(写入应该是正确的)rn13368202891rn13368202892rn13368202893rn13368202894rn13368202895rn但是从数据库中读取数据,写入2.txt后,该文件少了几个字符,这是什么呢?rn文件2.txt的内容变成如下:(第一排少了1336这几个字符)rn 8202891rn13368202892rn13368202893rn13368202894rn13368202895rn//读取文本文件到数据库rnvoid CFileSaveSqlDlg::OnButton1() rnrn CFile imagefile; rn if(0 == imagefile.Open("F:\\1.txt",CFile::modeRead)) rn return; rn _RecordsetPtr pRs = NULL; rn _ConnectionPtr pConnection = NULL; rn _variant_t varChunk; rn HRESULT hr; rn BYTE* pbuf; rn long nLength = imagefile.GetLength(); rn pbuf = new BYTE[nLength+20]; rn if(pbuf == NULL) rn return; //allocate memory error; rn imagefile.Read(pbuf,nLength); //read the file into memory rn rnrnrn BYTE *pBufEx; rn pBufEx = pbuf; rn //build a SAFFERRAY rn SAFEARRAY* psa; rn SAFEARRAYBOUND rgsabound[1]; rn rgsabound[0].lLbound = 0; rn rgsabound[0].cElements = nLength; rn psa = SafeArrayCreate(VT_UI1, 1, rgsabound); rn rn for (long i = 0; i < nLength; i++) rn SafeArrayPutElement (psa, &i, pBufEx++); rn VARIANT varBLOB; rn varBLOB.vt = VT_ARRAY | VT_UI1; rn varBLOB.parray = psa; rn rn _bstr_t strCnn("Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Password=zjj;Initial Catalog=note;Data Source=127.0.0.1"); rn try rn rn //Open a connection rn pConnection.CreateInstance(__uuidof(Connection)); rn hr = pConnection->Open(strCnn,"","",NULL); //Connect a DataBase rn pRs.CreateInstance(__uuidof(Recordset)); rn pRs->Open("Test",_variant_t((IDispatch *) pConnection,true),adOpenKeyset,adLockOptimistic,adCmdTable); //Open a Table rn rn pRs->AddNew(); rn pRs->Fields->GetItem("content")->AppendChunk(varBLOB); rn pRs->Update(); rn pRs->Close(); rn pConnection->Close(); rn rn catch(_com_error &e) rn rn // Notify the user of errors if any. rn _bstr_t bstrSource(e.Source()); rn _bstr_t bstrDescription(e.Description()); rn CString sError; rn sError.Format("Source : %s \n Description : %s\n",(LPCSTR)bstrSource,(LPCSTR)bstrDescription); rn AfxMessageBox(sError); rn rnrn//从数据库中取出数据写入文件rnvoid CFileSaveSqlDlg::OnButton2() rnrn _RecordsetPtr pRs = NULL; rn _ConnectionPtr pConnection = NULL; rn _variant_t varChunk; rn HRESULT hr; rn VARIANT varBLOB; rn _bstr_t strCnn("Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;User ID=sa;Password=zjj;Initial Catalog=note;Data Source=127.0.0.1"); rn try rn rn //Open a connection rn pConnection.CreateInstance(__uuidof(Connection)); rn hr = pConnection->Open(strCnn,"","",NULL); rn pRs.CreateInstance(__uuidof(Recordset)); rn pRs->Open("Test",_variant_t((IDispatch *) pConnection,true),adOpenKeyset,adLockOptimistic,adCmdTable); rn //read data rn long lDataLength = pRs->Fields->GetItem("content")->ActualSize; rn varBLOB = pRs->GetFields()->GetItem("content")->GetChunk(lDataLength); rn if(varBLOB.vt == (VT_ARRAY | VT_UI1)) rn rn BYTE *pBuf = NULL; rn pBuf = (BYTE*)GlobalAlloc(GMEM_FIXED,lDataLength); rn SafeArrayAccessData(varBLOB.parray,(void **)pBuf); rn //Build a File in Windows Temp Directory rn char tmpPath[_MAX_PATH+1]; rn GetTempPath(_MAX_PATH,tmpPath); rn CString strFileName = "F:\\2.txt"; rn // strFileName = tmpPath+strFileName; rn rn CFile outFile(strFileName,CFile::modeCreate|CFile::modeWrite); rn LPSTR buffer = (LPSTR)GlobalLock((HGLOBAL)pBuf); rn outFile.WriteHuge(buffer,lDataLength); rn GlobalUnlock((HGLOBAL)pBuf); rn outFile.Close(); rn SafeArrayUnaccessData (varBLOB.parray); rn rn rn pRs->Close(); rn pConnection->Close(); rn rn catch(_com_error &e) rn rn // Notify the user of errors if any. rn _bstr_t bstrSource(e.Source()); rn _bstr_t bstrDescription(e.Description()); rn CString sError; rn sError.Format("Source : %s \n Description : %s\n",(LPCSTR)bstrSource,(LPCSTR)bstrDescription); rn AfxMessageBox(sError); rn rn rn 论坛

没有更多推荐了,返回首页