欢迎来到HugNew-拥抱变化,扫一扫右边二维码关注微信订阅号:Martin说 或 加QQ群:427697041互相交流,Stay hungry, Stay foolish.

springmvc采用uploadify方式实现上传功能

spring Martin 3240℃ 0评论

web项目上传功能是很常见的功能,而实现上传功能的方式有好多,uploadify.js由于其浏览器兼容性及上传效果都挺不错所以现在应用很广泛,今天来说下采用uploadify.js插件方式实现上传功能的流程。

先说下我与之其他组件相比较用这个上传组件的原因:

优点:
1.工具就是为了方便使用和易于扩展
2.比swfuploader更易配置、控制和处理
3.比传统的ajaxuploadfile/jqform 实现原理和处理方式更安全
缺点:
多文件处理和好多函数处理过程都不是数组形式,所以导致多文件上传时文件处理在本地加载文件时交给了flash 进行队列轮询向Server发送请求

效果图

 通过查看官方文档我们可以很轻松的将插件嵌入到我们项目中,下面我们采用小demo的方式进行说明

前台调用uploadify.js插件脚本

/***uploadify上传接口调用,具体的使用接口参数使用请查看官方api***/
function getRootPath(){
    //获取当前网址
    var curWwwPath=window.document.location.href;
    //获取主机地址之后的目录
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //获取主机地址
    var localhostPaht=curWwwPath.substring(0,pos);
    //获取带"/"的项目名
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    projectName = "/hugnew";
    return(localhostPaht+projectName);
};

$(function(){
    uploadify();
});
var idName="";
function uploadify(){
    $("#file_upload").uploadify({  
        'height'        : 27,   
        'width'         : 80,    
        'buttonText'    : '添加附件',  
        'swf'           : getRootPath()+'/resources/js/uploadify/uploadify.swf?ver=' + Math.random(),  
        'uploader'      : getRootPath()+'/upload.do;jsessionid='+$("#sessionUID").val()+'?method=upload',  
        'auto'          : false, 
        'fileSizeLimit' : '30720KB', 
        'fileTypeExts'  : '*.doc; *.jpg; *.rar', 
        'cancelImg' :  getRootPath()+'/resources/js/uploadify/uploadify-cancel.png',
        'uploadLimit' : 3,
        'onUploadStart' : function(file) {
        },  
        'onUploadSuccess':function(file, data, response){  
             //回调函数,服务器接收上传请求并处理后返回值
             $("#tempFileName").val(file.name);
             $("#"+idName).val(data);
        },  
        'onUploadComplete':function(){  
        }  
    });  
}
function startUpload(name){  
         idName=name;    
         $('#file_upload').uploadify('upload','*');  
}

前台上传文件页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>hugnew.com,this is a uploadify demo</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!-- 公共JS&CSS开始 -->
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/resources/js/easyui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/resources/js/easyui/themes/icon.css">
    <link rel="stylesheet" type="text/css" href='${pageContext.request.contextPath}/resources/css/style/style.css'/>
    <script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/easyui/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/easyui/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/aircrewhealthjs/commonUI.js"></script>
    <!-- 公共JS&CSS结束 -->
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/resources/css/uploadify.css">
    <script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/uploadify/jquery.uploadify-3.1.min.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/uploadify/uploadify.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/json2.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/aircrewhealthjs/physical/physical.js"></script>
</head>
<body>
<input id='sessionUID' value='<%=session.getId()%>' type="hidden"/>
    <table id="nhc01_infoGrid2"></table>
    <div id="nhc01_editInfoDiv2" style="padding: 5px; width: 890px; height: 457px;">
    <fieldset>
    <legend>hugnew.com</legend>
    <form id="fileUploadForm" name = "fileUploadForm" method="post" action="physical.do?method=physicalInitSave" enctype="multipart/form-data"> 
    <table class="divTable">
    <tr>
    <td>附件名:</td>
    <td><input id="tempFileName" readonly="readonly" class="easyui-validatebox" required="true" style="width:300px;_width:300px; " />
    <input id="personnel" name="personnel" type="hidden"/>
    </td>
    </tr>
    <tr>
    <td>文件上传:</td>
    <td><input type="file" name="uploadify" id="file_upload" /><hr>  
    <a class="easyui-linkbutton" onclick="startUpload('personnel');" href="javascript:void(0);">开始上传</a>   
    <a href="javascript:$('#file_upload').uploadify('cancel', '*')" class="easyui-linkbutton">取消所有上传</a>   
    </td>
    </tr>  
    </table>
    <div id="viewBtn">
    <a class="easyui-linkbutton" icon="icon-ok" onclick="submitFormC()">保存</a>
    <a class="easyui-linkbutton" icon="icon-redo" id="Init_rest"> 重置</a>
    </div>
     </form>
    </fieldset>
    </div>
</body>
</html>

applicationContext-mvc.xml 配置

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
        <property name="defaultEncoding" value="utf-8"></property>        
    </bean>

服务器controller层接收上传请求处理

package com.hugnew.upload.action;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
@RequestMapping("/upload.do")
public class uploadAction {
    @RequestMapping(params = "method=index", method = RequestMethod.GET)
    public String index() {
        return "upload/index";
    }
    @SuppressWarnings("unused")
    @RequestMapping(params = "method=upload", method = RequestMethod.POST)
    public @ResponseBody String upload(HttpServletRequest request, HttpServletResponse response) {
        String responseStr="";  
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    
        //获取前台传值  
        String[] userNames = multipartRequest.getParameterValues("userName");  
        String[] contents = multipartRequest.getParameterValues("content");  
        String userName="";  
        String content="";  
        if(userNames!=null){  
            userName=userNames[0];  
        }  
        if(contents!=null){  
            content=contents[0];  
        }  
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();    
        String ctxPath= HNAServletContextListener.getSYS_UPLOADPATH_PATH();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");  
        String ymd = sdf.format(new Date());  
        ctxPath += ymd + "/";  
        //创建文件夹  
            File file = new File(ctxPath);    
            if (!file.exists()) {    
                file.mkdirs();    
            }    
            String fileName = null;
            String path=null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {    
                // 上传文件名     
                MultipartFile mf = entity.getValue();    
                fileName = mf.getOriginalFilename();  
                String strEnc = DesEncrypt.aircrewhealthGetEncString(fileName);// 加密字符串,返回String的密文
                String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");// 返回一个随机UUID。
                String suffix = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf("."), file                Name.length()) : null;
                String newFileName = strEnc + "-" + uuid + (suffix!=null?suffix:"");// 构成新文件名。
                File uploadFile = new File(ctxPath + newFileName);    
                try {  
                    FileCopyUtils.copy(mf.getBytes(), uploadFile); 
                    path =ctxPath+newFileName;
                responseStr="上传成功";  
            } catch (IOException e) {  
                responseStr="上传失败";  
                e.printStackTrace();  
            }    
            }   
           
            return path;  
    }
}

当然uploadify.js也不是完美的。在浏览器使用中也存在着一些小问题,如下:

1.chrome浏览器崩溃现象

原因:Chrome浏览器为了提高用户访问同一页面的速度,会对页面数据进行缓存,当(Javascript文件)url请求地址不变时会导致浏览器不发送请求,直接从缓存中读取之前的数据,可能uploadify.js文件走了缓存,导致某个变量为null导致chrome崩溃。

解决方案:根据stackoverflow上的帖子,给js文件加上随机参数,欺骗chrome浏览器防止缓存,使每次都发起请求。

<script src="/Resources/uploadify/jquery.uploadify3.1Fixed.js?ver=<%=(new Random()).Next(0, 99999).ToString() %>" type="text/javascript"></script>

参考:Caching uploadify files crashes the chrome

2.在Firefox中出现HTTP 404 Not Found错误

原因:症结在于 SWFUpload,这个是Uploadify调用供支持Flash上传用的,但是其没有对button_image_url进行判断,导致如果button_image_url为空的话就默认请求了当前根路径。

解决方案:

将下面代码:

this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);

修改成:

if (this.settings.button_image_url != "") {
    this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
}

参考:Uploadify v3 bug. Unecessary request when there is no button_image_url set

uploadify官方地址

转载请注明:HugNew » springmvc采用uploadify方式实现上传功能

喜欢 (8)or分享 (0)
发表我的评论
取消评论

表情