利用jsp+uploadify插件实现附件上传到ftp服务器的功能
来源:互联网 发布:linux 创建网络接口 编辑:程序博客网 时间:2024/06/06 01:12
千万注意:一定要注释掉springmvc配置文件里面关于文件上传的代码,不然获取不到要上传的文件列表!!!!折腾死了
这个周中午闲暇的时候研究了一下uploadify插件的使用,主要是想要实现一个附件上传的功能,看之前公司同事好像用过这个插件,但是见人家挺忙的,我只能找到她写的源码自己研究了,好来,话不多说,先把实现的效果贴出来给大家看看:
这是还未点击上传附件的界面(图:1)
当点击选择附件界面会弹出文件选择对话框如下:
选择好要上传的文件点击打开按钮,文件开始上传:
上传完成之后界面如下(上传进度条消失):
**由上面的效果图可以看出我做的这个附件上传整体效果是:
点击附件上传按钮–>选择要上传的文件–>上传文件—>显示上传文件的文件列表**
(一)、下载uploadify插件
Uploadify是JQuery的一个上传插件,实现的效果非常不错,带进度显示。不过官方提供的实例时php版本的,下面我用jsp+servlet简单实现了这个功能,你可以通过下面我分享的连接下载uoploadify文件:
下载jsp版本uploadify(我自己使用的文件)
(二)、下载插件安装包后,可以看到里面文件夹的几个主要文件:
(1)jquery.uploadify.js:完成上传功能的脚本文件,在调用页面引用(上传插件)
(2)uploadify.css:上传控件样式表,外观样式表
(3)uploader.swf:上传控件的主体文件,flash控件
(4)jquery.uploadify.min.js:压缩版的上传插件,部署时使用
(三)、项目环境介绍
我是在myeclipse下创建的java web的maven项目,搭建了springMVC的框架
说到这里我们需要的uploadify插件和运行环境就准备好了,我想很多人和我一样在最开始肯定会想到我们平时上传附件的时候一些场景,比如说我们上传资料到百度云盘时候的过程ps:如果想不起来可以自己去百度云盘上传文件体验一次,哈哈,可能不同的的人在思考上传附件这个功能的实现的时候会有不同的问题或者想法,就我来说我当时其实最好奇的是上传的附件到底最后是上传到了哪里,如果是上传到自己本地,肯定第不可能的,因为这样的话换台电脑找不到对应的位置上传肯定就会出问题,我想这个存放文件的地方一定是不管在哪里都可以访问的到的,因为文件上传了必然会存在一个文件下载的过程,我们在访问网页的时候会看到有很多地址链接,你一点击就会把相应的文件下载下来,这背后肯定就会有一个地址是我们下载对应文件的路径,知道了路径我们才能下载,但是想到这里我还是不知道要怎么做,不知道笔者们有没有人也思考过这个问题,因为我对java算是新手入门,项目经验很浅,对我来说这还真的算是个小白,怀着疑问我又赶紧上网查资料,可是却没有找到我觉得有价值的信息,郁闷了好一会儿,突然想起来我手上还有源码呢,赶快去里面找找有没有什么线索,果然皇天不负有心人,我发现了一个在src/main/resources/目录下有一个名叫:ftpconfig.properties的文件,我顺着这个文件继续钻,发现同事是把上传的附件存放在ftp服务器上面的,然后百度了ftp服务器的相关资料惊喜的发现了:原来我们可以创建一个远程ftp服务器,然后在连接ftp服务器,在登陆ftp服务器,登陆成功就可以将文件上到这个服务器,关于ftp服务器相关的资料童鞋们可以自己问问度娘,哈哈,一般来说公司有上传文件需求的都会创建自己的ftp服务器供大家使用,总之如果你要在项目中要连接ftp服务器你需要实现一下步骤:
(1)、ftpconfig.properties文件配置一些ftp服务器中的参数信息:
(2) 在ReadIniInfo类中对ftp.properties的加载处理,并初始化ftp连接,并建立连接
ReadIniInfo.java:
/**** @描述: 读取配置文件 */public class ReadIniInfo { private InputStream is; private Properties properties; //初始化配置文件 public ReadIniInfo() { properties = new Properties(); //读取配置文件:ftpconfig.properties is = this.getClass().getResourceAsStream("/ftpconfig.properties"); try { properties.load(is); } catch (FileNotFoundException e) { System.out.println("配置文件不存在.."); e.printStackTrace(); } catch (IOException e) { System.out.println("读取配置文件错误:" + e.getMessage()); e.printStackTrace(); } finally { try { if (null != is) { is.close(); } } catch (IOException e) { System.out.println("关闭链接失败.."); e.printStackTrace(); } } } /** * 获取FTP服务器地址 */ public String getFtpServer() { return properties.getProperty("ftpServer"); } /** * 获取FTP服务器端口 */ public String getFtpPort() { return properties.getProperty("ftpPort"); } /** * 获取FTP用户账号 */ public String getFtpUser() { return properties.getProperty("ftpUser"); } /** * 获取FTP用户密码 */ public String getFtpPwd() { return properties.getProperty("ftpPwd"); } /** * 获取ftp目的地仓库地址 */ public String getFtpRemotePath() { return properties.getProperty("ftpRemotePath"); } /** * http和ftp上传时的固定路径部份 */ public String getPathConstant() { return properties.getProperty("pathConstant"); } /** * 图片资源管理图片路径 */ public String getImageCenter() { return properties.getProperty("imagecenter"); } /** * 压缩图 */ public String getCompress() { return properties.getProperty("compress"); } /** * 公文管理的附件路径 */ public String getGwgl() { return properties.getProperty("gwgl"); }}
(4) 定义ftp接口类,提供登陆等相关接口,用于登陆ftp服务器
/*** @描述: ftp接口类 */public interface FtpService { /** * 登陆FTP服务器 */ public void login(FTPClient ftpClient, ReadIniInfo iniInfo) throws Exception; /** * 断开服务器链接 */ public void logout(FTPClient ftpClient) throws Exception; /** * 上传本地文件 */ public void uploadFile(FTPClient ftpClient, String remotePath, String fileNewName, InputStream inputStream, ReadIniInfo iniInfo) throws Exception; /** * 远程文件列表 */ public List<Map<String, String>> listFile(FTPClient ftpClient, String remotePath) throws Exception; /** * 下载远程文件 */ public InputStream downFileByFtp(FTPClient ftpClient, String remotePath, String fileName) throws Exception; /** * * @描述:删除文件 */ public void delFile(FTPClient ftpClient, String pathName) throws Exception;}
ftp各个接口的具体实现:
/*** @描述: ftp接口实例类 */@Servicepublic class FtpServiceImpl implements FtpService { /** * 登陆FTP服务器 */ public void login(FTPClient ftpClient, ReadIniInfo iniInfo) throws Exception { //获取FTP服务器地址 String ftpServer = iniInfo.getFtpServer(); //获取FTP服务器端口 String ftpPort = iniInfo.getFtpPort(); //获取FTP用户账号 String ftpUser = iniInfo.getFtpUser(); //获取FTP用户密码 String ftpPwd = iniInfo.getFtpPwd(); try { // 链接到FTP服务器 ftpClient.connect(ftpServer, Integer.valueOf(ftpPort)); System.out.println("链接到FTP服务器:" + ftpServer + "成功.."); // 开始登陆服务器 boolean boo = ftpClient.login(ftpUser, ftpPwd); if (boo) { System.out.println("登陆到FTP服务器:" + ftpServer + "成功.."); } else { System.out.println("登陆到FTP服务器:" + ftpServer + "失败.."); logout(ftpClient);//退出/断开FTP服务器链接 } } catch (Exception e) { e.printStackTrace(); System.err.println("登陆到FTP服务器:" + ftpServer + "失败.."); } } /** * 上传本地文件 * @param fileNewName 文件更改后的名称 * @throws Exception */ public void uploadFile(FTPClient ftpClient, String pathConstant, String fileNewName, InputStream inputStream, ReadIniInfo iniInfo) throws Exception { try { String ftpRemotePath = iniInfo.getFtpRemotePath();//ftp目的地仓库位置,而文件实例地址=仓库位置+上传指定位置 //设置被动模式 // 设置PassiveMode传输 ftpClient.enterLocalPassiveMode(); // 设置以二进制流的方式传输 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //设置字符集 ftpClient.setControlEncoding("GBK"); //创建目录结构 if (pathConstant != null && !"".equals(pathConstant.trim())) { String[] pathes = pathConstant.split("/"); for (String onepath : pathes) { if (onepath == null || "".equals(onepath.trim())) { continue; } onepath = new String(onepath.getBytes("GBK"), "iso-8859-1"); if (!ftpClient.changeWorkingDirectory(onepath)) { ftpClient.makeDirectory(onepath);//创建FTP服务器目录 ftpClient.changeWorkingDirectory(onepath);//改变FTP服务器目录 } } } boolean boo = ftpClient.storeFile(new String(fileNewName.getBytes("GBK"), "iso-8859-1"), inputStream); if (boo) { System.out.println("文件上传成功.."); } else { System.out.println("文件上传失败.."); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != inputStream) { inputStream.close(); } logout(ftpClient);//退出/断开FTP服务器链接 } catch (IOException e) { System.out.println("关闭链接失败.."); e.printStackTrace(); } } } /** * 远程文件列表 */ public List<Map<String, String>> listFile(FTPClient ftpClient, String remotePath) throws Exception { //设置目录字符集 String remp = new String(remotePath.getBytes("GBK"), "iso-8859-1"); FTPListParseEngine engine = ftpClient.initiateListParsing(remotePath); List<FTPFile> remoteFiles = Arrays.asList(engine.getNext(25)); List<Map<String, String>> list = new ArrayList<Map<String, String>>(); if (remoteFiles != null && remoteFiles.size() != 0) { System.out.println("目录" + remotePath + "下的文件列表.."); } else { System.out.println("目录" + remotePath + "下无文件内容.."); } //递归目录文件 for (FTPFile ftpFile : remoteFiles) { Map<String, String> map = new HashMap<String, String>(); map.put("fileName", ftpFile.getName());//文件名称 map.put("fileSize", Long.toString(ftpFile.getSize()));//文件大小 //文件时间 map.put("fileTime", new SimpleDateFormat("yyyy/MM/dd kk:mm:ss").format(ftpFile.getTimestamp().getTime())); list.add(map); } logout(ftpClient);//退出/断开FTP服务器链接 return list; } public InputStream downFileByFtp(FTPClient ftpClient, String remotePath, String fileName) throws Exception { FTPFile[] fs; InputStream is = null; try { //设置被动模式 ftpClient.enterLocalPassiveMode(); // 设置以二进制流的方式传输 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); //设置编辑格式 ftpClient.setControlEncoding("GBK"); remotePath = remotePath.substring(0, remotePath.lastIndexOf(fileName)); fs = ftpClient.listFiles(remotePath);//递归目标目录 for (FTPFile ff : fs) { if (ff.getName().equals(fileName)) {//查找目标文件 is = ftpClient .retrieveFileStream(new String((remotePath + fileName).getBytes("GBK"), "iso-8859-1")); break; } } } catch (IOException e) { e.printStackTrace(); } return is; } /** * 退出/断开FTP服务器链接 */ public void logout(FTPClient ftpClient) throws Exception { ftpClient.logout();//退出登陆 System.out.println("已退出FTP远程服务器.."); if (ftpClient.isConnected()) { ftpClient.disconnect();//断开链接 System.out.println("已断开FTP服务器链接.."); } } /** * * @描述:删除文件 */ public void delFile(FTPClient ftpClient, String pathName) throws Exception { try { boolean boo = ftpClient.deleteFile(pathName); if (boo) { System.out.println("文件删除成功.."); } else { System.out.println("文件删除失败.."); } } catch (Exception e) { e.printStackTrace(); } finally { //logout(ftpClient);//退出/断开FTP服务器链接 } }}
以上主要是主要完成两件事:
1、下载uploadify插件
2、tp服务器的相关需要的类和配置文件
现在真正开始实现上传文件的过程:
(四)、实现步骤:
(4.1)、创建uploadify.jsp文件
(4.2)、在uploadify.jsp文件引入uploadify插件相关的文件
(4.3)上传附件界面(uploadify.jsp的部分)
(4.4)前台编码(uploadify.jsp的部分)
初始化uploadify插件
可能截图有些看不清楚:小主也没有办法
大家如果想看uploadify.jsp源码的话点这里下载噢
uploadify插件的相关参数点这里参阅
(4.5)后台处理前台发过来的请求上传的请求
@Controller@RequestMapping(value="uploadify")public class UploadifyController { @Autowired private FtpService ftpService ; private static String FTP_ROOT_PATH = "document_manage"; /** * * @功能描述 附件上传 */ @RequestMapping(value = "/upload.action") public void upload(HttpServletRequest request, HttpServletResponse response) { JSONObject result = new JSONObject(); try { //创建一个通用的多部分解析器 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //判断 request 是否有文件上传,即多部分请求 if (multipartResolver.isMultipart(request)) { //转换成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)multipartResolver.resolveMultipart(request); //取得request中的所有文件名 Iterator<String> iter = multiRequest.getFileNames(); //登陆FTP ReadIniInfo iniInfo = new ReadIniInfo(); FTPClient ftpClient = new FTPClient(); ftpService.login(ftpClient, iniInfo); JSONArray upResult = new JSONArray(); while (iter.hasNext()) { //取得上传文件 MultipartFile file = multiRequest.getFile(iter.next()); if (file != null) { //当前上传文件的文件名称 String fileName = file.getOriginalFilename(); //当前上传文件的文件类型 //String fileType = file.getContentType(); //当前上传文件的文件大小 Long fileSize = file.getSize(); //当前上传文件的文件后缀 String suffix = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf("."), fileName.length()) : null; //如果名称不为“”,说明该文件存在,否则说明该文件不存在 if (!StringUtils.isBlank(fileName)) { //创建文件对象 TbDocumentFile myFile=new TbDocumentFile(); //重命名上传后的文件名 String saveFileName = Identities.uuid2() + suffix; //定义上传路径 String savePath = FTP_ROOT_PATH + "/" + DateUtils.Format("yyyyMMdd", new Date()) + "/"; //当前上传文件信息 JSONObject fileInfo = new JSONObject(); fileInfo.put("Fileoriginalname", fileName); fileInfo.put("Filename", saveFileName); fileInfo.put("Filesize", fileSize); fileInfo.put("Filesuffix", suffix); fileInfo.put("Filepath", savePath); fileInfo.put("id", Identities.uuid()); try { ftpService.uploadFile(ftpClient, savePath, saveFileName, file.getInputStream(), iniInfo); fileInfo.put("success", true); } catch (Exception e) { e.printStackTrace(); fileInfo.put("success", false); fileInfo.put("msg", "系统异常,上传失败!"); fileInfo.put("exception", e.getMessage()); } upResult.add(fileInfo); } } } result.put("upResult", upResult); } result.put("success", true); result.put("msg", "上传成功!"); } catch (Exception e) { e.printStackTrace(); result.put("success", false); result.put("msg", "系统异常,上传失败!"); result.put("exception", e.getMessage()); } ResponseUtils.renderJson(response, result.toString(), "encoding:UTF-8"); }}
至此上传附件到ftp服务器成功,在这里我着重想要总结一下我在实现的过程中遇到的问题,主要是关于当上传成功之后显示上传成功的文件列表这个部分:
//itemTemplate是uploadify插件的一个参数是用来设置上传队列的html模板的,我们可以自己定义想要显示的模板var itemHTML = itemTemplate; for ( var d in itemData) { //d表示itemData的每个属性(如:filedID、fileName等),itemData[d]表示相应属性(filedID)对应的值 //new RegExp()是正则表达式 itemHTML = itemHTML.replace(new RegExp( '\\{' + d + '\\}', 'g'), itemData[d]); }
下面截图就是alert(itemHTML)显示的内容:
累死宝宝了,先写到这里了。
- 利用jsp+uploadify插件实现附件上传到ftp服务器的功能
- 利用jsp+uploadify插件实现删除上传到ftp服务器里面的文件
- 利用jsp+uploadify插件实现附件下载
- Uploadify实现多附件上传功能
- Jsp实现附件上传功能
- JSP + Servlet 实现的文件上传到服务器的功能
- uploadify上传文件插件动态传参数到服务器
- 利用uploadify直接上传到upyun服务器上
- 利用FileZilla上传文件到ftp服务器
- Jsp中Uploadify插件的使用(jQuery上传插件)
- JSP中Uploadify插件的使用(jQuery上传插件)
- Spring SpringMVC 环境下上传文件到服务器,插件使用的uploadify
- Laravel 5.2 利用 Uploadify 插件实现上传图片
- JAVA实现FTP服务器文件的上传,下载,删除功能
- java实现文件上传ftp服务器功能
- Jquery上传插件uploadify的使用(JSP)版
- springMVC + swfupload 附件上传功能的实现
- springMVC + swfupload 附件上传功能的实现
- spring和springmvc的配置文件整合
- 多线程编程
- dojo 多选下拉框
- 事务
- nethogs按进程查看流量占用
- 利用jsp+uploadify插件实现附件上传到ftp服务器的功能
- 找工作笔试面试那些事儿(9)---数据库知识总结(1)
- 用 @ModelAttribute 出现The request sent by the client was syntactically incorrect.的解决办法
- CUDA之——指针的认识
- import CSV data into MySQL via PyMySQL in Python 3.3
- 7、使用序列化实现对象的拷贝
- mysql订单表如何设计?
- 解决 输入框input width 在IE8和chrome 显示不一样
- word-wrap和word-break的区别