附件上传下载删除

form前台

<input type="file" name="file" />

    function checkinfo(param){
	var proid=/*[[${applypro.proid}]]*/;
	 applyproform.action="../middleevaluate/insertmsg"+proid+"/"+param;
	 applyproform.submit();
	}
提交所有参数

  	
    @RequestMapping(value = "/insertmsg{status}")
    public String insertmsg(@PathVariable("status") String status ,@RequestParam("file") MultipartFile[] files,Model model, HttpServletRequest request,@ModelAttribute("dto") ApplyproDto pr,HttpServletResponse response){
	response.setHeader("X-Frame-Options", "SAMEORIGIN");
	//获取用户登录名
	UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	String loginname=userDetails.getUsername();

	User userInfo = uiservice.findByLoginName(loginname);
	
	pr.setProid(ToolUtil.getUUID());
	pr.setUserid(userInfo.getUserId());
	pr.setUserdept(userInfo.getDeptid());
	pr.setIschild("1");

	
	applyproservice.insertAndsaveApply(pr);
	if(files!=null&&files.length>0){  
            //循环获取file数组中得文件  
            for(int i = 0;i<files.length;i++){  
                MultipartFile file = files[i];  
                //保存文件  
                saveApplyproFile(file,pr);  
            }  
        }  
	
	return "redirect:/applypro/msglist";
    }

上传正式方法

 private void saveApplyproFile(MultipartFile file, ApplyproDto pr) {
	ApplyprofileDto applyproFileDto=new ApplyprofileDto();
      //  String rootPath="e:/shzz/shenbaofile";
	String rootPath = shenbaofilePath;
	
	File rootPathTest=new File(rootPath);
	if (!rootPathTest.exists()) {
	    rootPathTest.mkdirs();
	   }
	String fileName = file.getOriginalFilename();
	String serverFileName = "";
	if(fileName!=null&&!"".equals(fileName)){
	    serverFileName = System.currentTimeMillis()+fileName.substring(fileName.indexOf("."), fileName.length());
	    byte[] bytes;
		try {
			bytes = file.getBytes();
			File outfile=new File(rootPath+File.separator+serverFileName);
			
			FileCopyUtils.copy(bytes, outfile);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		applyproFileDto.setId(ToolUtil.getUUID());
		applyproFileDto.setApplypro(new Applypro(pr));
		applyproFileDto.setFilename(fileName);
		applyproFileDto.setFileurl(rootPath+"/"+serverFileName);
		applyproFileService.insertapplyproFile(applyproFileDto);
	
	}
	
    }

下载附件
前台

  function downloadmpg(id){
        	  
        	  window.open("../middleevaluate/downfile"+id,"_blank");
        	   
        	   
           }
         
  @RequestMapping(value="downfile{id}")
    public void  applyprofileDown(HttpServletRequest request,HttpServletResponse response,@PathVariable("id") String id)
    {
	
	//获取要下载的文件
	Applyprofile applyproFile =applyproFileService.findApplyproFileById(id);
	
		
	String fileName="",fileurl="";
	
	if(applyproFile!=null){
	    fileName=applyproFile.getFilename();
	    fileurl=applyproFile.getFileurl();
	    File file = new File(fileurl);
	        byte[] buf = new byte[1024 * 1024 * 10];  
	        int len = 0; 
	        ServletOutputStream ut = null;
	        BufferedInputStream br = null;  
	        response.reset();  
	   
	        response.setHeader("Pragma", "No-cache");  
	        response.setHeader("Cache-Control", "must-revalidate, no-transform,max-age=0");  
	        response.setDateHeader("Expires", 0L);  
	       
	        
	        String userAgent = request.getHeader("User-Agent"); 

	        boolean ie = (userAgent.toLowerCase().indexOf("msie") > -1 || userAgent.toLowerCase().indexOf("rv:11") > -1);
	        boolean isIE = (userAgent != null) && ie; 
	         
	        String displayFilename = file.getName();
	        response.setContentType("application/x-download"); 
	        if (isIE) {  
	            try {
	                displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
	            } catch (UnsupportedEncodingException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }  
	            
	            response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");  
	        } else {  
	            try {
	                displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
	            } catch (UnsupportedEncodingException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }  
	            response.setHeader("Content-Disposition", "attachment;filename=" + displayFilename);  
	        } 
	        try {
	            br = new BufferedInputStream(new FileInputStream(file));
	            ut = response.getOutputStream();  
	            while ((len = br.read(buf)) != -1)  
	                ut.write(buf, 0, len);
	        } catch (FileNotFoundException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        } 
	    
	}
	    
	 
	
    }

删除附件
前台

  function deleteFilempg(id){
        	  
        	   $("#"+id).remove();
        	   var applyprofile = {};
       		var applyprofileArray = new Array(1);
       		applyprofile.fileid=id;
       		applyprofileArray[0] = applyprofile;
       		$.ajax({
       	        url : "../middleevaluate/deleteFile",
       	        dataType: "json",
       	        data:{
       	      	  models : JSON.stringify(applyprofileArray)
       	        },
       	        type:"POST",
       	        success: function(result) {
       	        	if(result.ajaxResultJson.success){
       	        		alert(result.ajaxResultJson.msg);
       	        		
       	        	 	
       	        	}else{
       	        		alert(result.error);
       	        	}
       	   
       	        },
       	        error: function(result) {
       	      	  alert("系统异常");
       	        }
       	  });
       	    return false;
        	   
        	   
           }
 @RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
	public AjaxResultJson deleteFile(Model model,@RequestParam("models") String models) 
	{
		AjaxResultJson result = new AjaxResultJson();
		result.setSuccess(false);
		List<ApplyprofileDto> list = new ArrayList<ApplyprofileDto>();
		if(models!=null && models.length()>0)
		{
			try 
			{
				list = objectMapper.readValue(models,new TypeReference<List<ApplyprofileDto>>() {});
			} 
			catch (JsonParseException e) 
			{
				log.error("JsonParseException{}:", e.getMessage());
				model.addAttribute("error", e.getMessage());
			} 
			catch (IOException e)
			{
				log.error("IOException{}:", e.getMessage());
				model.addAttribute("error", e.getMessage());
			}
		}
		if (!model.containsAttribute("error")) 
		{
			try {
				if(list!=null && list.size()>0){
				    ApplyprofileDto dto = list.get(0);
				    dto=new ApplyprofileDto(applyproFileService.findApplyproFileById(dto.getId()));
				    File file=new File(dto.getFileurl());
				    file.delete();
				    applyproFileService.deleteApplyproFileById(dto.getId());
				   
					   
				    result.setMsg("删除成功!");
				    result.setSuccess(true);	
				}
				
				
		
			} catch (Exception e) {
				result.setMsg("删除失败,文件不存在 !");
				result.setSuccess(false);
				log.error("Exception{}:", e.getMessage());
				model.addAttribute("error", e.getMessage());
				result.setMsg( e.getMessage());
			}
			
		}
		return result;
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值