spring boot 使用kindeditor上传传照片到nginx

 

可以批量上传图片

一、前后台

1.1 引入

        <script src="/js/appjs/apply/jquery-1.12.4.min.js" type="text/javascript" charset="utf-8"></script>
         <link href="/kindeditor/themes/default/default.css" type="text/css" rel="stylesheet">
        <script charset="utf-8" src="/kindeditor/kindeditor-all.js"></script>
        <script charset="utf-8" src="/kindeditor/lang/zh_CN.js"></script>

 

1.2 初始化组建

<script>
            KindEditor.ready(function(K) {
                var editor = K.editor({
                    filePostName:"uploadFile",//上传组件名
                    uploadJson: '/apply/pic/upload',//上传地址
                    dir:"image"//类型

                });
                K('#J_selectImage').click(function() {
                    editor.loadPlugin('multiimage', function() {
                        editor.plugin.multiImageDialog({
                            clickFn : function(urlList) {
                                var div = K('#J_imageView');
                                div.html('');
                                K.each(urlList, function(i, data) {
                                    div.append('<img src="' + data.url + '">');
                                });
                                editor.hideDialog();
                            }
                        });
                    });
                });


<input type="button" style="width:100px;height:50px;"  id="J_selectImage" value="批量上传" />
                    
<div id="J_imageView">

 

1.3 上传的方法

@RequestMapping(value="/pic/upload",method=RequestMethod.POST,produces=MediaType.TEXT_PLAIN_VALUE)
    @ResponseBody
    public String upload(@RequestParam("uploadFile") MultipartFile uploadFile , 
            HttpServletRequest request,HttpServletResponse response) throws Exception {
        String sessionId = request.getSession().getId();
        System.out.println("调用上传");
        Map result = picService.uploadPicture(uploadFile,sessionId);
        String json = JsonUtils.objectToJson(result);
        return json;
    }

 

二、公共ftp方法

注意:ftp 前面是没有http的


//加载配置文件的值
@Value("${FTP_ADDRESS}")
private String FTP_ADDRESS;
@Value("${FTP_PORT}")
private int FTP_PORT;
@Value("${FTP_USERNAME}")
private String FTP_USERNAME;
@Value("${FTP_PASSWORD}")
private String FTP_PASSWORD;
@Value("${FTP_BASEPATH}")
private String FTP_BASEPATH;
@Value("${IMAGE_BASE_URL}")
private String IMAGE_BASE_URL;

 

FTP_ADDRESS: 47.98.184.30
FTP_PORT: 21
FTP_USERNAME: ftpuser
FTP_PASSWORD: ftpuser
FTP_BASEPATH: /home/ftpuser/img




@Override
public Map uploadPicture(MultipartFile uploadFile,String sessionId) { Map resultMap = new HashMap<>(); // 修改文件名 String oldName = uploadFile.getOriginalFilename(); System.out.println("oldName=" + oldName); String newName = IDUtils.genImageName() + oldName.substring(oldName.lastIndexOf(".")); System.out.println("newName=" + newName); // 上传文件到ftp服务器 String filePath = new DateTime().toString("/yyyy/MM/dd"); try { boolean uploadResult = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASEPATH, filePath, newName, uploadFile.getInputStream()); if(!uploadResult) { // error 成功是0 失败是1 resultMap.put("error", 1); resultMap.put("message", "上传失败"); return resultMap; } // 上传成功 resultMap.put("error", 0); String saveUrl = filePath + "/" + newName; System.out.println("url=" + saveUrl); resultMap.put("url", IMAGE_BASE_URL + saveUrl); ApplyImgExample example = new ApplyImgExample(); Criteria createCriteria = example.createCriteria(); createCriteria.andSessionidEqualTo(sessionId); List<ApplyImg> imgList = applyImgMapper.selectByExample(example); System.out.println("imgList size" + imgList.size()); if(imgList != null && imgList.size() > 0){ ApplyImg applyImg = imgList.get(0); if(StringUtils.isBlank(applyImg.getImgpath2())){ applyImg.setImgpath2(saveUrl); applyImgMapper.updateByPrimaryKeySelective(applyImg); } else { applyImg.setImgpath3(saveUrl); applyImgMapper.updateByPrimaryKeySelective(applyImg); } } else { ApplyImg applyImg = BeanUtils.getApplyImg(saveUrl, sessionId); applyImgMapper.insert(applyImg); } return resultMap; } catch (IOException e) { e.printStackTrace(); resultMap.put("error", 1); resultMap.put("message", "上传出现异常"); return resultMap; } }

package com.bootdo.apply.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

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) {
        System.out.println("host=" + host + "port"+ port);
        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)) {
                System.out.println("a "+ 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(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;
    }
    
    /** 
     * 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) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());

                    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;
    }
    
    public static void main(String[] args) {
        try {  
            FileInputStream in=new FileInputStream(new File("D:\\temp\\0.jpg"));  
            boolean flag = uploadFile("47.98.184.30", 21, "ftpuser", "ftpuser", "/home/ftpuser/img","/2015/01/21", "0.jpg", in);  
            System.out.println(flag);  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }  
    }
}

 

posted @ 2018-05-07 10:19  lyon♪♫  阅读(385)  评论(0编辑  收藏  举报