jeecg通用文件上传案例

当前主要用于调用uploadView.jsp方式进行文件上传

在需要文件上传的表单里面加入点击事件,调用commonUpload(回调,inputId,填充NameID,sizeId,用户id);方法,传递相应的参数即可复用

//通用弹出式文件上传
//callback 文件上传后的回调函数
//inputId  当前文件上传控件的name值
//nameId   当前上传文件的表单文件名称name值
//sizeId   当前上传文件的大小name值
//userId   当前上传文件的用户name值
//这些参数需要在文件上传成功后回调,用于callback方法内
function commonUpload(callback,inputId,nameId,sizeId,userId){
    $.dialog({
           content: "url:supplierController.do?commonUpload",
           lock : true,
           title:"文件上传",
           zIndex:getzIndex(),
           width:700,
           height: 200,
           parent:windowapi,
           cache:false,
       ok: function(){
               var iframe = this.iframe.contentWindow;
                //调用uploadview.jsp的方法
               iframe.uploadCallback(callback,inputId,nameId,sizeId,userId);
               return true;
       },
       cancelVal: '关闭',
       cancel: function(){
       } 
   });
}
//通用弹出式文件上传-回调
//给当前页面的控件赋值
function commonUploadDefaultCallBack(url,name,size,userName,inputId,nameId,sizeId,userId){
   //生成下载文件节点,绑定地址,通过servlet下载,防止游览器直接解析
	$("#"+inputId+"_href").attr('href',"supplierController/filedownload.do?path="+url+"&fileName="+name).html('下载');
	$("#"+inputId).val(url);
	$("[name='"+nameId+"']").val(name);
	$("[name='"+sizeId+"']").val(size);
	$("[name='"+userId+"']").val(userName);
	$("#"+inputId).parent().next().find(".saveMe").show();
}

uploadview.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="/context/mytags.jsp"%>
<!DOCTYPE html >
<html>
 <head>
<t:base type="jquery,easyui,tools"></t:base>
<script type="text/javascript">

        function uploadSuccess(d,file,response){
                //上传成功后,将服务器返回的值回填到uploadView.jsp的隐藏input控件内
                $("#fileUrl").val(d.attributes.url);
                $("#fileName").val(d.attributes.name);
                $("#swfpath").val(d.attributes.swfpath);
                $("#filesize").val(d.attributes.filesize);
                $("#userName").val(d.attributes.userName);
                var url = $("#fileUrl").val();
                var html="";
                if(url.indexOf(".gif")!=-1 || 
                                url.indexOf(".jpg")!=-1        ||
                                url.indexOf(".png")!=-1 ||
                                url.indexOf(".bmp")!=-1){
                        html += "<img src='"+url+"' width =400 height=300 />";
                }else{
                        html += "<a href='"+url+"' target=_blank >下载:"+d.attributes.name+"</a>";
                }
                $("#fileShow").html(html);
        }
        function uploadCallback(callback,inputId,nameId,sizeId,userId){
                //从隐藏的控件内取出值
                var url = $("#fileUrl").val();//文件上传后的路径
                var name= $("#fileName").val();//上传的文件名称
                var swfpath = $("#swfpath").val();//后台拼的地址,鬼知道干嘛
                var size= $("#filesize").val();//上传的文件大小,
                var userName= $("#userName").val();//上传文件的姓名,
                //调用上个页面的commonUploadDefaultCallBack方法
                callback(url,name,size,userName,inputId,nameId,sizeId,userId,swfpath);
                
        }
</script>
</head>
 <body style="overflow-x: hidden">
  <table cellpadding="0" cellspacing="1" class="formtable">
  <input id="documentTitle" type="hidden" name="documentTitle" value="blank"/>
  <input id="fileUrl" type="hidden"/>
  <input id="fileName" type="hidden"/>
  <input id="swfpath" type="hidden">
  <input id="filesize" type="hidden">
   <input id="userName" type="hidden">
   <tbody>
    <tr>
     <td align="right">
       <label class="Validform_label"></label>
     </td>
     <td class="value">
      <t:upload name="instruction" dialog="false" multi="false" extend="" queueID="instructionfile" view="false" auto="true" uploader="supplierController.do?ajaxSaveFile" onUploadSuccess="uploadSuccess"  id="instruction" formData="documentTitle"></t:upload>
     </td>
    </tr>
    <tr>
     <td colspan="2" id="instructionfile" class="value">
     </td>
    </tr>
   </tbody>
  </table>
   <div id="fileShow" >
  </div>
 </body>
 </html>

控制器方法,文件上传

	/**
	 * 自动上传保存附件资源的方式
	 * @return
	 */
	@RequestMapping(params = "ajaxSaveFile")
	@ResponseBody
	public AjaxJson ajaxSaveFile(MultipartHttpServletRequest request) {
		AjaxJson ajaxJson = new AjaxJson();
		Map<String, Object> attributes = new HashMap<String, Object>();
		try {
			Map<String, MultipartFile> fileMap = request.getFileMap();
			String uploadbasepath = ResourceUtil.getConfigByName("uploadpath");
			// 文件数据库保存路径
			String path = uploadbasepath + "/";// 文件保存在硬盘的相对路径
			String realPath = request.getSession().getServletContext()
                               .getRealPath("/") + "/" + path;// 文件的硬盘真实路径
			realPath += DateUtils.getDataString(DateUtils.yyyyMMdd) + "/";
			path += DateUtils.getDataString(DateUtils.yyyyMMdd) + "/";
			File file = new File(realPath);
			if (!file.exists()) {
				file.mkdirs();// 创建文件时间子目录
			}
			if(fileMap != null && !fileMap.isEmpty()){
				for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				    MultipartFile mf = entity.getValue();// 获取上传文件对象
					String fileName = mf.getOriginalFilename();// 获取文件名
					String swfName = PinyinUtil.getPinYinHeadChar(oConvertUtils
                                    .replaceBlank(FileUtils
                                    .getFilePrefix(fileName)));// 取文件名首字母作为SWF文件名
					String extend = FileUtils.getExtend(fileName);// 获取文件扩展名
					String noextfilename=DateUtils.getDataString(
                                    DateUtils.yyyymmddhhmmss)+StringUtil.random(8);//自定义文件名称
					String myfilename=noextfilename+"."+extend;//自定义文件名称
					String savePath = realPath + myfilename;// 文件保存全路径
					write2Disk(mf, extend, savePath);
					TSAttachment attachment = new TSAttachment();
					attachment.setId(UUID.randomUUID().toString().replace("-", ""));
					attachment.setAttachmenttitle(fileName);
					attachment.setCreatedate(new Timestamp(new Date().getTime()));
					attachment.setExtend(extend);
					attachment.setRealpath(path + myfilename);
					attachment.setSwfpath( path + 
                            FileUtils.getFilePrefix(myfilename) + ".swf");
					SwfToolsUtil.convert2SWF(savePath);

					systemService.save(attachment);
                    //返回文件存在的路径
					attributes.put("url", path + myfilename);
                    //返回上传文件名
					attributes.put("name", fileName);
                    //返回文件大小
					attributes.put("filesize", (int)(mf.getSize()/1024));
                    //返回上传用户名称
					attributes.put("userName",                                              
                     ResourceUtil.getSessionUser().getRealName());
					attributes.put("swfpath", attachment.getSwfpath());
				}
			}
			ajaxJson.setAttributes(attributes);
		} catch (Exception e) {
			e.printStackTrace();
			ajaxJson.setSuccess(false);
			ajaxJson.setMsg(e.getMessage());
		}
		return ajaxJson;
	}
	/**
     * 文件上传通用跳转
     *
     * @param req
     * @return
     */
    @RequestMapping(params = "commonUpload")
    public ModelAndView commonUpload(HttpServletRequest req) {
            return new ModelAndView("collection/base/uploadView");
    }
    /**
	 * 保存文件的具体操作
	 * @param mf
	 * @param extend
	 * @param savePath
	 * @throws IOException
	 * @throws UnsupportedEncodingException
	 * @throws FileNotFoundException
	 */
	private void write2Disk(MultipartFile mf, String extend, String savePath)
			throws IOException, UnsupportedEncodingException, FileNotFoundException {
		File savefile = new File(savePath);
		if("txt".equals(extend)){
			//利用utf-8字符集的固定首行隐藏编码原理
			//Unicode:FF FE   UTF-8:EF BB   
			byte[] allbytes = mf.getBytes();
			try{
				String head1 = toHexString(allbytes[0]);
				String head2 = toHexString(allbytes[1]);
				if("ef".equals(head1) && "bb".equals(head2)){
					//UTF-8
					String contents = new String(mf.getBytes(),"UTF-8");
					if(StringUtils.isNotBlank(contents)){
						OutputStream out = new FileOutputStream(savePath);
						out.write(contents.getBytes());
						out.close();
					}
				}  else {
					//GBK
					String contents = new String(mf.getBytes(),"GBK");
					OutputStream out = new FileOutputStream(savePath);
					out.write(contents.getBytes());
					out.close();
				}
			  } catch(Exception e){
				  String contents = new String(mf.getBytes(),"UTF-8");
					if(StringUtils.isNotBlank(contents)){
						OutputStream out = new FileOutputStream(savePath);
						out.write(contents.getBytes());
						out.close();
					}
			}
		} else {
			FileCopyUtils.copy(mf.getBytes(), savefile);
		}
	}
	private String toHexString(int index){
        String hexString = Integer.toHexString(index);   
        // 1个byte变成16进制的,只需要2位就可以表示了,取后面两位,去掉前面的符号填充   
        hexString = hexString.substring(hexString.length() -2);  
        return hexString;
	}

文件下载

   @RequestMapping("/filedownload")
    public void download(HttpServletResponse response,HttpServletRequest request,
        String  path,String fileName){
    	 try {
            //tomcat自动编码导致中文乱码处理
			fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			logger.info("解码失败");
		}
        //设置响应头类型
        response.setContentType("multipart/form-data");
        //设置文件头、要保存的文件名称
        if(!StringUtil.isEmpty(path)){
        if(StringUtil.isEmpty(fileName)){
        	fileName="无名称"+path.substring(path.lastIndexOf("."));
        }
        try {
        //fileName等于下载后的文件名,包括后缀
        	 response.setHeader("Content-Disposition","attachment;
                                fileName="+new StringBuffer("").append(
                                new  String(fileName.getBytes("gb2312"),
                                "ISO-8859-1")).append("")+"");
		} catch (Exception e) {
		}
        OutputStream outputStream = null;
        FileInputStream inputStream = null;
        //把文件路径转换为文件对象
        path  = request.getSession().getServletContext().getRealPath("/") + "/" +path;
        File file = new File(path);
        try {
            //将文件转换为流
        	try {
        		inputStream = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				logger.error(fileName+"不存在");
			}
            outputStream = response.getOutputStream();
            int b = -1;
            //设置文件流缓冲区
            byte[] bytes = new byte[1024];
            while ((b=inputStream.read(bytes)) != -1){
                //将文件写入输出流
                outputStream.write(bytes,0,b);
            }
            //强制将文件流刷出缓冲区
            outputStream.flush();
        } catch (IOException e) {
        	logger.error(fileName+"下载失败");
        }finally {
            try {
                //关闭流
            	if(inputStream!=null)
            		inputStream.close();
            	if(outputStream!=null)
            		outputStream.close();
            systemService.addLog(ResourceUtil.getSessionUser().getUserName()
        +"下载了文件:"+fileName, Globals.Log_Type_OTHER, Globals.Log_Leavel_INFO);
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
 
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_38197447/article/details/81237545