前端使用KindEditor,后台使用Springmvc
1 拷貝KindEditor相關文件到項目中
拷貝KindEditor相關文件到項目中
2 准備一個jsp頁面
頁面中我准備了一個超鏈接,點擊就可以打開KindEditor批量圖片上傳對話框
1.jsp頁面中需要引入KindEditor相關的css和js文件。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>KindEditor UploadDemo</title> <!-- 引入kindeditor的css文件 --> <link href="/js/kindeditor-4.1.10/themes/default/default.css" type="text/css" rel="stylesheet"> <!-- 引入kindeditor的js文件 --> <script type="text/javascript" charset="utf-8" src="/js/kindeditor-4.1.10/kindeditor-all-min.js"></script> <script type="text/javascript" charset="utf-8" src="/js/kindeditor-4.1.10/lang/zh_CN.js"></script> <script type="text/javascript"> //點擊上傳圖片,打開一個KindEditor上傳圖片的對話框。 function uploadFileFunction() { KindEditor.editor({ //指定上傳文件參數名稱 filePostName : "uploadFile", //指定上傳文件請求的url。 uploadJson : '/pic/upload', //上傳類型,分別為image、flash、media、file dir : "image" }).loadPlugin('multiimage', function() { var editor = this; editor.plugin.multiImageDialog({ }); }); } </script> </head> <body> <a href="javascript:uploadFileFunction()">上傳圖片</a> </body> </html>
頁面效果如下:
3 后台PictureController
KindEditor的批量上傳圖片功能,實際上也是一個也給上傳,多個圖片,每個圖片
都會執行下面的方法。需要把commons-io\fileupload的jar包添加到工程中。
maven工程中添加下面的依賴:
下面代碼中的圖片是上傳到了圖片服務器里面,當然也可以修改傳到其它地方。
package cn.e3mall.controller; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import cn.e3mall.common.utils.FastDFSClient; import cn.e3mall.common.utils.JsonUtils; /** * @title:PictureController * @description: * @author jepson * @date 2018年5月30日 下午4:20:36 * @version 1.0 */ @Controller public class PictureController { @Value("${IMAGE_SERVER_URL}") private String IMAGE_SERVER_URL; @RequestMapping(value = "/pic/upload",produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8") @ResponseBody @SuppressWarnings("all") public String uploadFile(MultipartFile uploadFile) { try { // 1、取文件的擴展名 String originalFilename = uploadFile.getOriginalFilename(); String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); // 2、創建一個FastDFS的客戶端 FastDFSClient client = new FastDFSClient("classpath:conf/client.conf"); // 3、執行上傳處理 String path = client.uploadFile(uploadFile.getBytes(), extName); // 4、拼接返回的url和ip地址,拼裝成完整的url String url = IMAGE_SERVER_URL + path; // 5、返回map Map result = new HashMap<>(); result.put("error", 0); result.put("url", url); //把java對象轉換成json字符串 String json = JsonUtils.objectToJson(result); return json; } catch (Exception e) { e.printStackTrace(); // 5、返回map Map result = new HashMap<>(); result.put("error", 1); result.put("message", "圖片上傳失敗"); //把java對象轉換成json字符串 String json = JsonUtils.objectToJson(result); return json; } } }
JsonUtils工具類代碼

package cn.e3mall.common.utils; import java.util.List; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; /** * * @title:JsonUtils * @description:json轉換工具類,使用的是jackson * @author jepson * @date 2018年5月29日 下午9:16:16 * @version 1.0 */ public class JsonUtils { // 定義jackson對象 private static final ObjectMapper MAPPER = new ObjectMapper(); /** * 將對象轉換成json字符串。 * <p>Title: pojoToJson</p> * <p>Description: </p> * @param data * @return */ public static String objectToJson(Object data) { try { String string = MAPPER.writeValueAsString(data); return string; } catch (JsonProcessingException e) { e.printStackTrace(); } return null; } /** * 將json結果集轉化為對象 * * @param jsonData json數據 * @param clazz 對象中的object類型 * @return */ public static <T> T jsonToPojo(String jsonData, Class<T> beanType) { try { T t = MAPPER.readValue(jsonData, beanType); return t; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 將json數據轉換成pojo對象list * <p>Title: jsonToList</p> * <p>Description: </p> * @param jsonData * @param beanType * @return */ public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) { JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType); try { List<T> list = MAPPER.readValue(jsonData, javaType); return list; } catch (Exception e) { e.printStackTrace(); } return null; } }
FastDFSClient工具類代碼

package cn.e3mall.common.utils; import org.csource.common.NameValuePair; import org.csource.fastdfs.ClientGlobal; import org.csource.fastdfs.StorageClient1; import org.csource.fastdfs.StorageServer; import org.csource.fastdfs.TrackerClient; import org.csource.fastdfs.TrackerServer; public class FastDFSClient { private TrackerClient trackerClient = null; private TrackerServer trackerServer = null; private StorageServer storageServer = null; private StorageClient1 storageClient = null; public FastDFSClient(String conf) throws Exception { if (conf.contains("classpath:")) { conf = conf.replace("classpath:", this.getClass().getResource("/").getPath()); } ClientGlobal.init(conf); trackerClient = new TrackerClient(); trackerServer = trackerClient.getConnection(); storageServer = null; storageClient = new StorageClient1(trackerServer, storageServer); } /** * 上傳文件方法 * <p>Title: uploadFile</p> * <p>Description: </p> * @param fileName 文件全路徑 * @param extName 文件擴展名,不包含(.) * @param metas 文件擴展信息 * @return * @throws Exception */ public String uploadFile(String fileName, String extName, NameValuePair[] metas) throws Exception { String result = storageClient.upload_file1(fileName, extName, metas); return result; } public String uploadFile(String fileName) throws Exception { return uploadFile(fileName, null, null); } public String uploadFile(String fileName, String extName) throws Exception { return uploadFile(fileName, extName, null); } /** * 上傳文件方法 * <p>Title: uploadFile</p> * <p>Description: </p> * @param fileContent 文件的內容,字節數組 * @param extName 文件擴展名 * @param metas 文件擴展信息 * @return * @throws Exception */ public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throws Exception { String result = storageClient.upload_file1(fileContent, extName, metas); return result; } public String uploadFile(byte[] fileContent) throws Exception { return uploadFile(fileContent, null, null); } public String uploadFile(byte[] fileContent, String extName) throws Exception { return uploadFile(fileContent, extName, null); } }
client.conf配置文件
tracker_server=192.168.25.133:22122
resources.properties配置文件
# 圖片服務器地址 IMAGE_SERVER_URL=http://192.168.25.133/
4 springmvc中配置文件上傳解析器
<!-- 定義文件上傳解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 設定默認編碼 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 設定文件上傳的最大值5MB,5*1024*1024 --> <property name="maxUploadSize" value="5242880"></property> </bean>
5 測試
1 點擊對話框中的添加圖片按鈕選擇需要上傳的圖片
2 點擊開始上傳
能夠回顯說明圖片已經上傳成功了,演示中的圖片是上傳到圖片服務器的。
3 如果希望點擊“全部插入”之后有另外的邏輯的話,可以在對話框中加入點擊事件
下面隨便給一個演示:
PictureController中使用ftpClient上傳到ftp服務器
package cn.e3mall.controller; import java.util.HashMap; import java.util.Map; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import cn.e3mall.common.utils.FtpUtils; import cn.e3mall.common.utils.IDUtils; import cn.e3mall.common.utils.JsonUtils; /** * @title:PictureController * @description: * @author jepson * @date 2018年5月30日 下午4:20:36 * @version 1.0 */ @Controller public class PictureController { /** * 使用ftp上傳圖片 */ @Value("${FTP_ADDRESS}") private String FTP_ADDRESS; //服務器地址 @Value("${FTP_PORT}") private Integer FTP_PORT; //端口 @Value("${FTP_USERNAME}") private String FTP_USERNAME; //連接ftp服務器用戶名 @Value("${FTP_PASSWORD}") private String FTP_PASSWORD; //密碼 @Value("${FTP_BASE_PATH}") private String FTP_BASE_PATH; //基本路徑 @Value("${FTP_IMAGE_BASE_URL}") private String FTP_IMAGE_BASE_URL; //服務器圖片的基本地址 @RequestMapping(value = "/pic/upload",produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8") @ResponseBody @SuppressWarnings("all") public String uploadFile(MultipartFile uploadFile) { Map resultMap = new HashMap<>(); try { //生成一個新的文件名 //取原始文件名 String oldName = uploadFile.getOriginalFilename(); //生成新文件名 //UUID.randomUUID(); String newName = IDUtils.genImageName(); newName = newName + oldName.substring(oldName.lastIndexOf(".")); //圖片上傳 String imagePath = new DateTime().toString("/yyyy/MM/dd"); boolean result = FtpUtils.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASE_PATH, imagePath, newName, uploadFile.getInputStream()); //返回結果 if(!result) { resultMap.put("error", 1); resultMap.put("message", "文件上傳失敗"); //為了保證功能的兼容性,需要把Result轉換成json格式的字符串。 String json = JsonUtils.objectToJson(resultMap); return json; } resultMap.put("error", 0); resultMap.put("url", FTP_IMAGE_BASE_URL + imagePath + "/" + newName); //為了保證功能的兼容性,需要把Result轉換成json格式的字符串。 String json = JsonUtils.objectToJson(resultMap); return json; } catch (Exception e) { resultMap.put("error", 1); resultMap.put("message", "文件上傳發生異常"); //為了保證功能的兼容性,需要把Result轉換成json格式的字符串。 String json = JsonUtils.objectToJson(resultMap); return json; } } /** * 使用fastdfs服務器 */ /* @Value("${IMAGE_SERVER_URL}") private String IMAGE_SERVER_URL; @RequestMapping(value = "/pic/upload",produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8") @ResponseBody @SuppressWarnings("all") public String uploadFile(MultipartFile uploadFile) { try { // 1、取文件的擴展名 String originalFilename = uploadFile.getOriginalFilename(); String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); // 2、創建一個FastDFS的客戶端 FastDFSClient client = new FastDFSClient("classpath:conf/client.conf"); // 3、執行上傳處理 String path = client.uploadFile(uploadFile.getBytes(), extName); // 4、拼接返回的url和ip地址,拼裝成完整的url String url = IMAGE_SERVER_URL + path; // 5、返回map Map result = new HashMap<>(); result.put("error", 0); result.put("url", url); //把java對象轉換成json字符串 String json = JsonUtils.objectToJson(result); return json; } catch (Exception e) { e.printStackTrace(); // 5、返回map Map result = new HashMap<>(); result.put("error", 1); result.put("message", "圖片上傳失敗"); //把java對象轉換成json字符串 String json = JsonUtils.objectToJson(result); return json; } } */ }
FtpUtils工具類
package cn.e3mall.common.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; /** * ftp文件傳輸工具欄 * @title:FtpUtil * @description: * @author jepson * @date 2018年6月2日 下午4:59:27 * @version 1.0 */ public class FtpUtils { /** * 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); ftp.setBufferSize(2048); //設置緩存大小2M //設置傳輸使用被動模式 ftp.enterLocalPassiveMode(); //上傳文件 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("C:/Users/jepson/Pictures/download/ad/ID1/ertong.jpg")); boolean flag = uploadFile("192.168.25.128", 21, "root", "264778", "/var/ftp/images","/2018/06/02", "yo.jpg", in); System.out.println(flag); } catch (FileNotFoundException e) { e.printStackTrace(); } } }