`

spring mvc使用uploadify上传

阅读更多

使用的uploadify 3.1 和easyUI

效果图

自己写得uploadify.js

复制代码
function getRootPath(){
    //获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath=window.document.location.href;
    //获取主机地址之后的目录,如: uimcardprj/share/meun.jsp
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //获取主机地址,如: http://localhost:8083
    var localhostPaht=curWwwPath.substring(0,pos);
    //获取带"/"的项目名,如:/uimcardprj
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    projectName = "/AircrewHealth";
    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, 
       // 'formData'      : {'userName':'','content':''},  
        'onUploadStart' : function(file) {
        },  
        'onUploadSuccess':function(file, data, response){  
            //alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
             $("#tempFileName").val(file.name);
             $("#"+idName).val(data);
        },  
        'onUploadComplete':function(){  
           // $('#importLispDialog').window('close');  
        }  
    });  
}
function startUpload(name){  
            idName=name;    
         $('#file_upload').uploadify('upload','*');  
}  
复制代码

jsp页面

复制代码
<%@ 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>招飞初检</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>体检录入</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>

action

复制代码
package com.hna.aircrewhealth.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;
import com.hna.framework.core.Listener.HNAServletContextListener;
import com.hna.framework.core.datasource.DesEncrypt;


@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) {
//        request = new MulpartRequestWrapper(request);
        
        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 = request.getSession().getServletContext().getRealPath("/")+ "\\" + "images\\";    
//            String ctxPath=request.getSession().getServletContext().getRealPath("/")+"uploads\\"; 
            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()) {    
                // 上传文件名    
                // System.out.println("key: " + entity.getKey());    
                MultipartFile mf = entity.getValue();    
                fileName = mf.getOriginalFilename();  
               //String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();      
               //SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");  
               // String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;  
                
                String strEnc = DesEncrypt.aircrewhealthGetEncString(fileName);// 加密字符串,返回String的密文
                String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");// 返回一个随机UUID。
                String suffix = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf("."), fileName.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 文件列表

其他的修改一下路径就可以了

原文链接:http://www.cnblogs.com/W203654/archive/2012/10/18/2728850.html

分享到:
评论

相关推荐

    spring mvc uploadify上传文件

    springMVC+uploadify上传图片。

    spring MVC uploadify

    spring mvc multipartResolver结合uploadify操作图片文件上传与预览

    uploadify [解决spring MVC上传配置冲突]

    uploadify的demo,解决spring MVC上传配置冲突。保留springmvc的配置,修改controller中的代码。

    J2EE spring mvc mybatis bootstrap HTML5 后台框架 控制台 mysql版本_spring3.0

    【源码】mysql版本_spring3.0 系统模块 1....服务器内部GET POST 请求 25.uploadify 上传插件,单条、批量上传,带进度条,异步,图片、视频, 其它文件格式均可上传 26.地图选点获取经纬度坐标,根据俩经纬度计算距离

    多张图片上传的例子,MVC项目

    例子为MVC项目。通过uploadify控件实现了 多张图片上传,有缩略图提示。

    J2EE spring mvc mybatis bootstrap HTML5 后台框架 控制台 oracle版本_spring3.0

    【源码】oracle版本_spring3.0 系统模块 1....服务器内部GET POST 请求 25.uploadify 上传插件,单条、批量上传,带进度条,异步,图片、视频, 其它文件格式均可上传 26.地图选点获取经纬度坐标,根据俩经纬度计算距离

    java 附件上传

    uploadify2.1.0 spring mvc java jsp代码

    SpringMVC + jquery.uploadify实现上传文件功能

    件上传是很多项目都会使用到的功能,SpringMVC当然也提供了这个功能。不过小编不建议在项目中通过form表单来提交文件上传,这样做的局限性很大。下面这篇文章主要介绍了利用SpringMVC + jquery.uploadify实现上传...

    java ssm内容管理系统

    后端 核心框架:Spring Framework 4.2.5.RELEASE 安全框架:Apache Shiro 1.3.2 视图框架:Spring MVC 4.2.5.RELEASE 数据库连接池:Tomcat JDBC ...文件上传 :jquery.uploadify 表单验证 :jquery.vali

    CMS轻量级系统

    天梯(tianti) Java 轻量级的 CMS 解决方案-天梯。天梯是一个用 Java 相关技术搭建的后台 CMS ... 文件上传 :jquery.uploadify 表单验证 :jquery.validator 展现树 :jquery.ztree html模版引擎 :template

    解决Tomcat的maxPostSize属性的配置需要注意的问题

    近期要做大文件上传功能,除了修改前端框架上传控件jQuery Uploadify的上传文件限制大小和Spring MVC框架配置的文件上传模块中的MultipartResolver中的文件上传限制大小,还需要去修改Nginx服务器中conf目录下的...

    style:Spring+SpringMVC +HibernateJPA

    style一、框架使用:1、后台框架:使用spring+spring mvc+hibernate jpa。2、前台框架:使用bootstrap V2。二、主要内容(持续更新。。。):1、对spring data jpa做二次封装生成公共Dao。2、自定义jsp标签。3、树...

Global site tag (gtag.js) - Google Analytics