• 文件的上传(可以上传照片,word文档,等单个文件)


    jsp:
    jsp页面:
    <LINK href="${basePath}plugins/uploadify/uploadify.css" type="text/css" rel="stylesheet" />
    <script language="javascript" type="text/javascript">
        //防止客户端缓存文件,造成uploadify.js不更新,而引起的“喔唷,崩溃啦”  
        document.write ("<script type='text/javascript' " + "src='${basePath}plugins/uploadify/jquery.uploadify.min.js?" + new Date () + "'></script>");
    </script>
    <style>
    .uploadify-box {
         130px;
        margin: 0px;
        margin-top: 10px;
    }
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@taglib prefix="f" uri="http://java.sun.com/jsp/jstl/fmt"%>
    <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
    
    <script type="text/javascript">
    <script type="text/javascript">
    $(function() {
    //文件上传 $('.uploadFile').each(function(){ var id= $(this).attr("id"); var $this = $(this); $("#"+id).uploadify({ buttonClass:'', fileSizeLimit: '20480KB', uploader: '${basePath}core/upload!uploadFile.action',// 服务器端处理地址 swf: '${basePath}js/uploadify/uploadify.swf',// 上传使用的 Flash buttonText: "上传文档", buttonCursor: 'hand', fileObjName: 'uploadify',// 上传参数名称 后台action里面的属性uploadify fileTypeExts: "*.jpg;*.png;*.gif;*.pdf;*.doc;*.docx", // 扩展名 fileTypeDesc: "请选择 文件格式", removeTimeout:1, // 文件说明 auto: true,// 选择之后,自动开始上传 multi: false, // 是否支持同时上传多个文件 queueSizeLimit: 1,// 允许多文件上传的时候,同时上传文件的个数 queueID:'queueID', onUploadSuccess:function(file, data, response){ var data =jQuery.parseJSON(data); if(data.error == 1){ ldDialog.alert(data.message); }else{ $("#filePath").val(data.url); $("#fileName").val(data.fileName); $("#userFileName").html(data.fileName); } } }); }); }); </script>
        @RequestMapping("core/upload!uploadFile.action")
        public void uploadFile(@RequestParam(value = "uploadify", required = false) MultipartFile uploadify,HttpServletRequest request,HttpServletResponse response,ModelMap modelMap) throws Exception {
    
            @SuppressWarnings("deprecation")
            String savePath = request.getRealPath("/")+ "/" + "upload/";
            String saveUrl = "upload/";
            HashMap<String, String> extMap = new HashMap<String, String>();
            extMap.put("file", "pdf,rar,zip,7z,gif,jpg,jpeg,png,bmp,doc,docx,xlsx,xls");
            //extMap.put("image", "gif,jpg,jpeg,png,bmp");
            extMap.put("csv", "csv");
             int uploadMaxSize =Integer.valueOf(optionService.getByOptionName(CoreValue.OPTION_UPLOAD_MAX_SIZE).getOptionValue());
            long maxSize = Long.valueOf(String.valueOf(uploadMaxSize)).longValue();
            String maxSizeKb = StringUtil.formatNumber(new Double(maxSize / 1024L),"0");
            response.setContentType("text/html; charset=UTF-8");
            String jsonString = "";
            if (!ServletFileUpload.isMultipartContent(getRequest())) {
                jsonString = getError("请选择文件。");
                response.getWriter().println(jsonString);
                return;
            }
    
            File uploadDir = new File(savePath);
            if (!uploadDir.isDirectory()) {
                jsonString = getError(savePath + "上传目录不存在。");
                response.getWriter().println(jsonString);
                return;
            }
    
            if (!uploadDir.canWrite()) {
                jsonString = getError("上传目录没有写权限。");
                response.getWriter().println(jsonString);
                return;
            }
    
            String dirName = getRequest().getParameter("dir");
            if (dirName == null) {
                dirName = "file";
            }
            if (!extMap.containsKey(dirName)) {
                jsonString = getError("目录名不正确。");
                response.getWriter().println(jsonString);
                return;
            }
    
            savePath = savePath + dirName + "/";
            saveUrl = saveUrl + dirName + "/";
            File saveDirFile = new File(savePath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String ymd = sdf.format(new Date());
            savePath = savePath + ymd + "/";
            saveUrl = saveUrl + ymd + "/";
            File dirFile = new File(savePath);
    
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
    
            String fileName = uploadify.getOriginalFilename();
            long fileSize = uploadify.getSize();
            if (fileSize > maxSize) {
                jsonString = getError("上传文件大小超过限制。最大为" + maxSizeKb + "kb");
                response.getWriter().println(jsonString);
                return;
            }
    
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                
            if (!Arrays.asList(((String) extMap.get(dirName)).split(",")).contains(fileExt)) {
                jsonString = getError("不允许的上传文件类型。");
                response.getWriter().println(jsonString);
                return;
            }
    
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "_"+ new Random().nextInt(1000) + "." + fileExt;
            File uploadedFile = null;
            try {
                uploadedFile = new File(savePath, newFileName);
                if(uploadedFile.exists()){
                    
                }
                if(!uploadedFile.exists()){
                    uploadedFile.mkdirs();
                }
                uploadify.transferTo(uploadedFile);
            } catch (Exception e) {
                jsonString = getError("上传文件失败。");
                response.getWriter().println(jsonString);
                return;
            }
            JSONObject obj = new JSONObject();
            obj.put("error", Integer.valueOf(0));
            obj.put("url", saveUrl + newFileName);
            obj.put("newFileName", newFileName);
            obj.put("fileName", fileName);
            jsonString = obj.toJSONString();
            response.getWriter().println(jsonString);
        }
    
        private String getError(String message) {
            JSONObject obj = new JSONObject();
            obj.put("error", Integer.valueOf(1));
            obj.put("message", message);
            return obj.toJSONString();
        }
  • 相关阅读:
    卡尔曼滤波器的简单推导
    data_quick 进度
    面试
    MapServer+TileCache+Apache+Python24 构建KS数据服务器
    PYTHONPATH 可以跨版本 方便使用 (本文为windows方法)转~
    20130923
    20130909
    error C2504 类的多层继承 头文件包含
    int long 等基础类型在不同平台的大小
    mysql python image 图像存储读取
  • 原文地址:https://www.cnblogs.com/lxnlxn/p/10007332.html
Copyright © 2020-2023  润新知