SpringMVC+SwfUpload进行多文件同时上传
由于最近项目需要做一个多文件同时上传的功能,所以好好的看了一下各种上传工具,感觉uploadify和SwfUpload的功能都比较强大,并且使用起来也很方便。SWFUpload是一个flash和js相结合而成的文件上传插件,而且该插件可以用在php、.net、Java等项目开发中。在使用的过程中需要引入两个js文件,并且进行相关参数的配置,同时也可以定义一系列的事件,如:上传成功事件,上传失败事件,正在上传事件等等。由于我在项目开发是使用SpringMVC进行的,所以下面我根据我自己的项目简述一下SwfUpload如何整合到Web项目中去。
首先说一下Swfupload相对于HTML中file标签上传的优点:
- 允许一次上传多个文件,但会有一个上传队列,队列里文件的上传是逐个进行的,服务器端接收文件时跟普通的表单上传文件是一样的(相当于表单一次提交了一个file,但是提交了多次,后台处理的时候只需要处理一次即可);
- 用flash进行上传,页面无刷新,且可自定义Flash按钮的样式, 类似AJAX的无刷新上传,里面可以引入swf文件实现动态效果;
- 可以显示上传进度,也可以在浏览器端就对要上传的文件格式,大小等进行配置(只需要配置一个参数即可,比用js的数据验证要好很多);
- 良好的浏览器兼容性并且兼容其他JavaScript库 (例如:jQuery,EXT, Prototype等);一般含有flash插件的即可正常运行,但是好像最低要求flash的版本要达到flash9;
- SwfUpload还提供了丰富的事件接口供开发者使用;开发者可以自定义各种和上传相关的事件;
SWfUpload实现文件的上传流程如下:
1、引入相应的js文件 (swfupload.js和swfupload.queue.js必须引入)
2、实例化SWFUpload对象,传入一个配置参数对象进行各方面的配置。
3、点击SWFUpload提供的Flash按钮(也可以更改配置信息中的button_image_url参数来配置自己的按钮),弹出文件选取窗口选择要上传的文件;
4、文件选取完成后符合规定的文件会被添加到上传的队列里;
5、调用startUpload方法让队列里文件开始上传;
6、文件上传过程中会触发相应的事件(想要触发什么事件需要自己定义,但是一般网上搜一下就可以了,大部分定义都相同,我也会贴出我的代码),开发者利用这些事件来更新ui、处理错误、发出提示等等;
下面说我的项目中SpringMVC+SwfUpload的配置过程及代码:
引入相应的JS文件后实例化SwfUpload对象(JS代码,一般嵌入到jsp文件中或者单独写一个文件引入到jsp页面内):
- var swfu;
- window.onload = function() {
- var settings = {
- flash_url : "swfupload/swfupload.swf",
- flash9_url : "swfupload/swfupload_fp9.swf",
- upload_url: "http://localhost:8080/ams/upload/fileUpload.do",
- post_params: {"PHPSESSID" : "aa"},
- file_size_limit : "100 MB",
- file_types : "*.*",
- file_post_name : "filedata",
- file_types_description : "All Files",
- file_upload_limit : 100,
- file_queue_limit : 0,
- custom_settings : {
- progressTarget : "fsUploadProgress",
- cancelButtonId : "btnCancel"
- },
- debug: true,
- // Button settings
- button_image_url: "images/TestImageNoText_65x29.png",
- button_width: "65",
- button_height: "29",
- button_placeholder_id: "spanButtonPlaceHolder",
- button_text: '<span class="theFont">Hello</span>',
- button_text_style: ".theFont { font-size: 16; }",
- button_text_left_padding: 12,
- button_text_top_padding: 3,
- // The event handler functions are defined in handlers.js
- swfupload_preload_handler : preLoad,
- swfupload_load_failed_handler : loadFailed,
- file_queued_handler : fileQueued,
- file_queue_error_handler : fileQueueError,
- upload_start_handler : uploadStart,
- upload_progress_handler : uploadProgress,
- upload_error_handler : uploadError,
- upload_success_handler : uploadSuccess
- };
- swfu = new SWFUpload(settings);
- };
编写相关的监听事件(JS代码,即html引入的handler.js文件):
- function preLoad() {
- if (!this.support.loading) {
- alert("You need the Flash Player 9.028 or above to use SWFUpload.");
- return false;
- }
- }
- function loadFailed() {
- alert("Something went wrong while loading SWFUpload. If this were a real application we'd clean up and then give you an alternative");
- }
- function fileQueued(file) {
- try {
- var progress = new FileProgress(file, this.customSettings.progressTarget);
- progress.setStatus("Pending...");
- progress.toggleCancel(true, this);
- } catch (ex) {
- this.debug(ex);
- }
- }
- function fileQueueError(file, errorCode, message) {
- try {
- if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
- alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
- return;
- }
- var progress = new FileProgress(file, this.customSettings.progressTarget);
- progress.setError();
- progress.toggleCancel(false);
- switch (errorCode) {
- case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
- progress.setStatus("File is too big.");
- this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
- break;
- case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
- progress.setStatus("Cannot upload Zero Byte files.");
- this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
- break;
- case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
- progress.setStatus("Invalid File Type.");
- this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
- break;
- default:
- if (file !== null) {
- progress.setStatus("Unhandled Error");
- }
- this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
- break;
- }
- } catch (ex) {
- this.debug(ex);
- }
- }
- function fileDialogComplete(numFilesSelected, numFilesQueued) {
- try {
- if (numFilesSelected > 0) {
- document.getElementById(this.customSettings.cancelButtonId).disabled = false;
- }
- /* I want auto start the upload and I can do that here */
- this.startUpload();
- } catch (ex) {
- this.debug(ex);
- }
- }
- function uploadStart(file) {
- try {
- /* I don't want to do any file validation or anything, I'll just update the UI and
- return true to indicate that the upload should start.
- It's important to update the UI here because in Linux no uploadProgress events are called. The best
- we can do is say we are uploading.
- */
- var progress = new FileProgress(file, this.customSettings.progressTarget);
- progress.setStatus("Uploading...");
- progress.toggleCancel(true, this);
- }
- catch (ex) {}
- return true;
- }
- function uploadProgress(file, bytesLoaded, bytesTotal) {
- try {
- var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
- var progress = new FileProgress(file, this.customSettings.progressTarget);
- progress.setProgress(percent);
- progress.setStatus("Uploading...");
- } catch (ex) {
- this.debug(ex);
- }
- }
- function uploadSuccess(file, serverData) {
- try {
- var progress = new FileProgress(file, this.customSettings.progressTarget);
- progress.setComplete();
- progress.setStatus("Complete.");
- progress.toggleCancel(false);
- } catch (ex) {
- this.debug(ex);
- }
- }
- function uploadError(file, errorCode, message) {
- try {
- var progress = new FileProgress(file, this.customSettings.progressTarget);
- progress.setError();
- progress.toggleCancel(false);
- switch (errorCode) {
- case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
- progress.setStatus("Upload Error: " + message);
- this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
- break;
- case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
- progress.setStatus("Upload Failed.");
- this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
- break;
- case SWFUpload.UPLOAD_ERROR.IO_ERROR:
- progress.setStatus("Server (IO) Error");
- this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
- break;
- case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
- progress.setStatus("Security Error");
- this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
- break;
- case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
- progress.setStatus("Upload limit exceeded.");
- this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
- break;
- case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
- progress.setStatus("Failed Validation. Upload skipped.");
- this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
- break;
- case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
- // If there aren't any files left (they were all cancelled) disable the cancel button
- if (this.getStats().files_queued === 0) {
- document.getElementById(this.customSettings.cancelButtonId).disabled = true;
- }
- progress.setStatus("Cancelled");
- progress.setCancelled();
- break;
- case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
- progress.setStatus("Stopped");
- break;
- default:
- progress.setStatus("Unhandled Error: " + errorCode);
- this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
- break;
- }
- } catch (ex) {
- this.debug(ex);
- }
- }
- function uploadComplete(file) {
- if (this.getStats().files_queued === 0) {
- document.getElementById(this.customSettings.cancelButtonId).disabled = true;
- }
- }
- // This event comes from the Queue Plugin
- function queueComplete(numFilesUploaded) {
- var status = document.getElementById("divStatus");
- status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
- }
编写HTML页面:
- <!DOCTYPE html>
- <html>
- <head>
- <title>SWFUpload Demos - Simple Demo</title>
- <link href="css/default.css" rel="stylesheet" type="text/css" />
- <script type="text/javascript" src="swfupload/swfupload.js"></script>
- <script type="text/javascript" src="swfupload/swfupload.queue.js"></script>
- <script type="text/javascript" src="js/fileprogress.js"></script>
- <script type="text/javascript" src="js/handlers.js"></script>
- <body>
- <div id="header">
- <h1 id="logo"><a href="../">SWFUpload</a></h1>
- <div id="version">v2.5.0</div>
- </div>
- <div id="content">
- <h2>External Interface Demo</h2>
- <form id="form1" action="index.php" method="post" enctype="multipart/form-data">
- <p> This page tests rebuilding the External Interface after some kind of display change. This demo isn't meant for building upon. Rather it
- helps test whether a particular browser is suffering from this bug.</p>
- <div class="fieldset flash" id="fsUploadProgress">
- <span class="legend">Upload Queue</span>
- </div>
- <div id="divStatus">0 Files Uploaded</div>
- <div id="divMovieContainer">
- <span id="spanButtonPlaceHolder"></span>
- <input type="button" value="Start Upload" onclick="swfu.startUpload();" style="margin-left: 2px; font-size: 8pt; height: 29px;" />
- </div>
- </form>
- </div>
- </body>
- </html>
后台处里代码:
首先要配置SpringMVC配置文件,在配置文件中加入下面内容
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!-- one of the properties available; the maximum file size in bytes -->
- <property name="maxUploadSize" value="10485760000000" />
- </bean>
服务器接收程序:
- @ResponseBody
- @RequestMapping("/fileUpload.do")
- public String fileUpload(HttpServletRequest request,@RequestParam("filedata")MultipartFile file) throws Exception {
- request.setCharacterEncoding("utf-8");//解决乱码问题
- try{
- String uploadDir = request.getServletContext().getRealPath("/upload");//获取上传目录的路径
- //获得目录,如果目录不存在,则创建目录
- File dirPath = new File(uploadDir);
- if (!dirPath.exists()) {
- dirPath.mkdirs();
- }
- //开始文件上传
- InputStream inputStream = file.getInputStream(); //获得输入流
- String fileName = file.getOriginalFilename(); //获得原始名字
- String fileNameFull = uploadDir + "/" + fileName;
- OutputStream outputStream = new FileOutputStream(fileNameFull);//获得输出流
- int bytesRead = 0;
- byte[] buffer = new byte[8192];
- while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1)
- {
- //输出到目标文件夹
- outputStream.write(buffer, 0, bytesRead);
- }
- outputStream.close();
- // close the stream
- inputStream.close();
- }catch(Exception e){
- e.printStackTrace();
- return "error";
- }
- return "ok";
- }
这样经过上面的配置即可完成多文件同时上传的例子了,注意的地方有几点:
一是中文名乱码问题,解决办法:
1.在Java程序内加入一行代码:request.setCharacterEncoding("utf-8");
2.进行编码转换,fileName = new String(fileName.getBytes("GBK"),"UTF-8");//反正就是进行编码的转换
3.好像还有其它的方法,但是我也不太懂了
还有一点是后台获得file的时候名字问题:
后台获得file是一个一个获取的,即如果你上传10个文件,那就是分十次来调用后台Java代码的,每次调用上传一个文件,所以后台只需要对一个文件进行处理即可,这些文件传递到后台的name属性值是相同的,通过 file_post_name : "filedata"来进行配置,这个时候后台获取file只要通过filedata即可了!
这是我初步了解了SwfUpload之后进行记录的内容,希望以后自己能回来翻看学习。
SpringMVC+SwfUpload进行多文件同时上传的更多相关文章
- 在SpringMVC框架下实现文件的 上传和 下载
在eclipse中的javaEE环境下:导入必要的架包 web.xml的配置文件: <?xml version="1.0" encoding="UTF-8" ...
- SpringMVC + AJAX 实现多文件异步上传
转自:https://www.jianshu.com/p/f3987f0f471f 今天,我就这个问题来写一篇如何用 SpringMVC + AJAX 实现的多文件异步上传功能.基本的代码还是沿用上篇 ...
- SWFUpload无刷新文件批量上传
一.首先将SWFUpload所有文件加入项目中,如图
- [Pulgin] 利用swfupload实现java文件批量上传
URL:http://blog.csdn.net/xuweilinjijis/article/details/8876305 之前在网上找过很多相关资料,很多所谓的批量上传都是忽悠人的,真正的批量上传 ...
- SpringMVC学习09(文件的上传和下载)
文件上传和下载 准备工作 文件上传是项目开发中最常见的功能之一 ,springMVC 可以很好的支持文件上传,但是SpringMVC上下文中默认没有装配MultipartResolver,因此默认情况 ...
- jquery文件批量上传控件Uploadify3.2(java springMVC)
人比較懒 有用为主 不怎么排版了 先放上Uploadify的官网链接:http://www.uploadify.com/ -->里面能够看到PHP的演示样例,属性说明,以及控件下载地址.分f ...
- SpringMVC进行文件的上传以及多文件的上传(转)
基本的SpringMVC的搭建在我的上一篇文章里已经写过了,这篇文章主要说明一下如何使用SpringMVC进行表单上的文件上传以及多个文件同时上传的步骤 SpringMVC 基础教程 框架分析:htt ...
- SpringMVC中文件的上传(上传到服务器)和下载问题(一)
一.今天我们所说的是基于SpringMVC的关于文件的上传和下载的问题的解决.(这里所说的上传和下载都是上传到服务器与从服务器上下载文件).这里的文件包括我们常用的各种文件.如:文本文件(.txt), ...
- SpringMVC框架(四)文件的上传下载,上下文路径
文件目录: SpringMVC配置文件: <?xml version="1.0" encoding="UTF-8"?> <beans xmln ...
随机推荐
- Java 8 Lambda表达式10个示例【存】
PS:不能完全参考文章的代码,请参考这个文件http://files.cnblogs.com/files/AIThink/Test01.zip 在Java 8之前,如果想将行为传入函数,仅有的选择就是 ...
- 解决 oracle 错误ORA-01033
数据库在导入数据的过程中,意外关机.重启机器后,pl/sql-developer不能登录数据库,报错ORA-01033:oracle initializationor shutdown in prog ...
- 创建 序列 存储过程 job
掌握了 oracle中的 dbms_lock 函数,该函数 主要用于暂停执行的程序 1.用意 写job 以10分钟 为单元,前10分钟 从 1到10 插入测试表, 中间10分钟从 11到20插入测试表 ...
- iOS几种简单有效的数组排序方法
第一种,利用数组的sortedArrayUsingComparator调用 NSComparator ,obj1和obj2指的数组中的对象 NSComparator cmptr = ^(id obj1 ...
- Xcode7新特性
更新Xcode7之后报错: Assertion failure in -[UIApplication _runWithMainScene:transitionContext:completion:], ...
- Js 旋转平滑特效
效果图 源码 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...
- qt二维码示例
原创文章,引用请保证原文完整性,尊重作者劳动,原文地址http://blog.csdn.net/hiwubihe/article/details/38679621,qq:1269122125. 移动终 ...
- MTP设备无法安装驱动的解决办法
1,进入设备管理器右击带黄色问号的MTP,选择“属性”,“详细信息”“设备范例 ID”(用Ctrl+C复制). 2,找到c:\windows\inf\wpdmtp.inf打开(或者通过运行打开),找到 ...
- 巧用Session Manager还原Firefox丢失会话
今天Firefox Crash之后,我的会话全部丢失了.按照以往来说,Firefox在重新启动之后或者Crash之后会有一个会话还原的页面.但今天确实没有.后来我进行Google查阅,试了很多种办法. ...
- 13_FCITX输入法安装及问题排查解决
使用linux最沮丧的事情莫过于中文输入法切换不出来,甚至有人错误地认为,要使用中文输入法,必须把“区域和语言”(Region & Language)设置为中国-中文.输入法只是一个软件,和区 ...