• uploadify springMVC


    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <c:set var="ctx" value="${pageContext.request.contextPath}"/>
    
    
    <script src="${ctx}/jslib/uploadify/jquery.uploadify.js" type="text/javascript" charset="utf-8"></script>
    
    <link href="${ctx}/jslib/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
    
    <script type="text/javascript">
        $(function() {
            
            //添加界面的附件管理
            $("#file_upload").uploadify({  
                'height'        : 27,   
                'width'         : 80,    
                'buttonText'    : '添加附件',
                'queueID': 'fileQueue',                        //队列的ID
                'queueSizeLimit':5,
                'swf'           : '${ctx}/jslib/uploadify/uploadify.swf',  
                'uploader'      : '${ctx}/fileUpload/uploadFile',  
                'auto'          : false,  
                'fileTypeExts'  : '*.rar',  
                'fileObjName'   : 'file',  
                'multi'   : true, 
                'removeCompleted': false,                       //是否完成后移除序列,默认为true
                'fileSizeLimit': '100MB',                       //单个文件大小,0为无限制,可接受KB,MB,GB等单位的字符串值
                'onUploadSuccess':function(file, data, response){ 
                    var vv = data.split('|');
                    var bb = $("input[name=attachmentIds]").attr('value');
                    bb +="," + vv[0];
                    $("input[name=attachmentIds]").attr('value',bb);
                    
                    bb = $("input[name=attachmentNames]").attr('value');
                    bb +="," + vv[1];
                    $("input[name=attachmentNames]").attr('value',bb);
                    //$.messager.alert("提示", "上传完毕!");  
                }
            }); 
            
            $('#documentId').combotree({
                url : '${ctx}/dictionarytype/tree?code=documenttype',
                parentField : 'pid',
                panelHeight : 'auto',
                onBeforeExpand : function(node, param) {
                    $('#documentId').combotree("tree").tree("options").url = "${ctx}/dictionarytype/trees?type=0&pId="
                            + node.id;
                
                }
            });
            $('#documentAddForm').form({
                url : '${ctx}/document/add',
                onSubmit : function() {
                    progressLoad();
                    
                    var isValid = $(this).form('validate');
                    if (!isValid) {
                        progressClose();
                    }else{
                        var bb = $("input[name=attachmentIds]").attr('value');
                        var num = $("#file_upload").data('uploadify').queueData.queueLength;
                        if(bb=="" && num>0){
                            progressClose();
                            $.messager.show({
                                title : '提示',
                                msg : '<div class="light-info"><div class="light-tip icon-tip"></div><div>'
                                        + "您你附件还没上传,请先上传附件!"
                                        + '</div></div>',
                                showType : 'show'
                            });
                            return false;
                        }
                    }
                    return isValid;
                },
                success : function(result) {
                    progressClose();
                    result = $.parseJSON(result);
                    if (result.success) {
                        parent.$.modalDialog.openner_dataGrid.datagrid('reload');//
                        $.messager
                        .show({
                            title : '提示',
                            msg : '<div class="light-info"><div class="light-tip icon-tip"></div><div>'
                                    + result.msg
                                    + '</div></div>',
                            showType : 'show'
                        });
                        parent.$.modalDialog.handler.dialog('close');
                    }else{
                        parent.$.messager.alert('提示', result.msg, 'warning');
                    }
                }
            });
            
        });
        
        function init(){
            var attachments = $("input[name=attachmentIds]").attr('value');
            $("input[name=attachmentIds]").attr('value',"");
            $('#file_upload').uploadify('cancel', '*');
            if(attachments!=""){
                $.post('${ctx}/fileUpload/deleteFile', {
                    attachments : attachments
                }, function(result) {
                    
                }, 'json');
            }
        }
    </script>
    <div style="padding: 3px;">
        <form id="documentAddForm" method="post">
            <table class="grid">
                <tr>
                    <td>标题</td>
                    <td  colspan="3"><input name="title" type="text" placeholder="请输入字典编码" class="easyui-validatebox" data-options="required:true" style=" 355px; height: 29px;" ></td>
                </tr>
                <tr>
                      <td>排序</td>
                    <td><input name="seq" value="0"  class="easyui-numberspinner" style=" 140px; height: 29px;" required="required" data-options="editable:false"></td>
                    <td>类别</td>
                    <td><select id="documentId" name="documentId" style=" 140px; height: 29px;" data-options="required:true"></select></td>
                </tr>
                <tr>
                    <td>备注</td>
                    <td colspan="3"><textarea name="content" rows="5" cols="50" ></textarea></td>
                </tr>
                <tr>
                    <td>文档附件</td>
                    <td colspan="3">
                        <input name="attachmentIds" id="attachmentIds" type="hidden"  class="easyui-validatebox" >
                        <input name="attachmentNames" id="attachmentNames" type="hidden"  class="easyui-validatebox" >
                        <input type="file" name="file_upload" id="file_upload"/>  
                        <a class="easyui-linkbutton" href="javascript:$('#file_upload').uploadify('upload', '*')">上传文件</a> | <a class="easyui-linkbutton" href="javascript:init()">取消上传</a>  
                    </td>
                    
                </tr>
            </table>
            <div id="fileQueue" class="fileQueue"></div>
        </form>
    package east.mvc.controller.file;
    
    
    package east.mvc.controller.file;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    import java.util.Random;
    import java.util.UUID;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.springframework.beans.factory.annotation.Autowired;
    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.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    
    import east.mvc.controller.base.BaseController;
    import east.mvc.framework.constant.GlobalConstant;
    import east.mvc.model.base.Graph;
    import east.mvc.model.sys.Tattachment;
    import east.mvc.pageModel.base.Grid;
    import east.mvc.pageModel.base.PageFilter;
    import east.mvc.pageModel.base.SessionInfo;
    import east.mvc.pageModel.sys.MapHistory;
    import east.mvc.service.basic.GraphServiceI;
    import east.mvc.service.sys.AttachmentServiceI;
    import east.mvc.service.sys.MapHistoryServiceI;
    import east.mvc.utils.StringUtil;
    
    @Controller
    @RequestMapping("/fileUpload")
    public class FileUploadController extends BaseController {
        private HttpServletRequest request = null;
    
        @Autowired
        private AttachmentServiceI attachmentService;
    
        @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
        public String uploadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
            this.request = request;
            String responseStr = "";
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // 获取前台传值
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            // String ctxPath =
            // request.getSession().getServletContext().getRealPath("/")+ "\" +
            // "images\";
            String configPath = File.separator + "upload" + File.separator;
            // String vv = getPhysicalPath(configPath);
            // String vv2 = getPhysicalPathByRoot(configPath);
            String ctxPath = request.getSession().getServletContext().getRealPath("/");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            String year = sdf.format(new Date());
            configPath += year + File.separator;
            sdf = new SimpleDateFormat("MM");
            String month = sdf.format(new Date());
            configPath += month + File.separator;
    
            ctxPath += configPath;
            // 创建文件夹
            File file = new File(ctxPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = 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;
                responseStr = configPath + newFileName + "|" + fileName;
                File uploadFile = new File(ctxPath + newFileName);
                try {
                    FileCopyUtils.copy(mf.getBytes(), uploadFile);
                } catch (IOException e) {
                    responseStr = "上传失败";
                    e.printStackTrace();
                }
    
            }
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            // 这句话的意思,是告诉servlet用UTF-8转码,而不是用默认的ISO8859
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(responseStr);
            return null;
        }
    
        @RequestMapping("/deleteFile")
        @ResponseBody
        public void getAreaIds(HttpServletRequest request, String attachments) {
            if (!attachments.equals("")) {
                String ctxPath = request.getSession().getServletContext().getRealPath("/");
                attachments = attachments.substring(1);
                String[] value = attachments.split(",");
                for (int i = 0; i < value.length; i++) {
                    File file = new File(ctxPath + "//" + value[i]);
                    file.delete();
                }
            }
        }
    
        @RequestMapping("/downloadFile")
        @ResponseBody
        public void downloadFile(HttpServletRequest request, HttpServletResponse response, String attachmentId) throws Exception{
            if (!attachmentId.equals("")) {
                Tattachment attachment = attachmentService.gets(attachmentId);
                if (attachment != null) {
                    String fileName = attachment.getFileName();
                    String filePath = attachment.getFilePath();
                    BufferedInputStream in = null;
                    BufferedOutputStream out = null;
                    request.setCharacterEncoding("UTF-8");
                    String rootpath = request.getSession().getServletContext().getRealPath("/");
                    try {
                        
                        File f = new File(rootpath + "//" + filePath);
                        response.setContentType("application/x-excel");
                        response.setCharacterEncoding("UTF-8");
                        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                        response.setHeader("Content-Length", String.valueOf(f.length()));
                        in = new BufferedInputStream(new FileInputStream(f));
                        out = new BufferedOutputStream(response.getOutputStream());
                        byte[] data = new byte[1024];
                        int len = 0;
                        while (-1 != (len = in.read(data, 0, data.length))) {
                            out.write(data, 0, len);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (in != null) {
                            in.close();
                        }
                        if (out != null) {
                            out.close();
                        }
                    }
                }
            }
        }
    
        /**
         * 根据传入的虚拟路径获取物理路径
         * 
         * @param path
         * @return
         */
        private String getPhysicalPath(String path) {
            String servletPath = this.request.getServletPath();
            String realPath = this.request.getSession().getServletContext().getRealPath(servletPath);
            return new File(realPath).getParent() + "/" + path;
        }
    
        /**
         * 根据传入的虚拟路径获取物理路径(相对应根路径)
         * 
         * @param path
         * @return
         * @author fengjx
         * @date 2014年3月10日
         */
        private String getPhysicalPathByRoot(String path) {
            String realPath = this.request.getSession().getServletContext().getRealPath("/");
            return new File(realPath).getPath() + "/" + path;
        }
    }
    
    
    
    http://files.cnblogs.com/files/xsmhero/uploadify.rar
  • 相关阅读:
    利用FlashPaper实现类似百度文库功能
    浅谈Oracle函数返回Table集合
    Oracle 触发器在日志管理开发中的应用
    Putty 工具 保存配置的 小技巧
    java.util.Date转java.sql.Date丢失时间问题
    java String和Date转换
    springboot项目使用拦截器修改/添加前端传输到后台header和cookie参数
    Spring的使用及Spring3.2控制器增强@ControllerAdvice
    使用fastjson统一序列化响应格式
    【转】Elastic-Job
  • 原文地址:https://www.cnblogs.com/xsmhero/p/4334285.html
Copyright © 2020-2023  润新知