标签: j2ee

  • 在J2EE中下载文件时使用中文名字的示例代码

        @RequestMapping(path = { "/downloadFromArchive" }, method={RequestMethod.GET})
        public ResponseEntity<byte[]> downloadFromArchive(HttpServletRequest request, HttpServletResponse response,
        			@RequestParam(required=false) String id
        		) throws IOException {
        	  
            HttpHeaders headers = new HttpHeaders();	//设置http协议头部
            
            if(id==null||id.equals("")){
            	return null;
            }
            
            Archive archive = this.archiveService.get(id);
            if(archive==null){
            	return null;
            }
            
            if(archive.getLink().indexOf(".")<0){
            	response.sendRedirect(archive.getLink());
            	return null;
            }
            String extension = archive.getLink().substring(archive.getLink().lastIndexOf("."));
            
            //System.out.println("archive.getTitle()"+archive.getTitle());
            //System.out.println("archive.getLink()"+archive.getLink());
            
            String fileName = archive.getTitle()+extension;
            //System.out.println("fileName = "+fileName);
            
            //获取文件在服务器上的绝对路径
    		String filePath = archive.getLink();
    		
    		//假如路径为阿新制作的下载controller,则执行特殊的操作,filePath会根据阿新的逻辑去获取
    		
    			
    		Pattern pattern = Pattern.compile(".*\\?archiveId=(.*?)&fileName=(.*)&randomName=(.*)");
    		Matcher	matcher = pattern.matcher(archive.getLink());
    		if(matcher.find()){
    			System.out.println("正则匹配成功1");
    			String archiveId = matcher.group(1);
    			fileName = matcher.group(2);
    			String randomName = matcher.group(3);
    			filePath = "/uploads/archiveFile/"+archiveId+"/"+randomName;
    			System.out.println("filePath" + filePath);
    		}
    		else{
    			pattern = Pattern.compile(".*\\?archiveId=(.*?)&fileName=(.*)");
    			matcher = pattern.matcher(archive.getLink());
    			if(matcher.find()){
    				System.out.println("正则匹配成功2");
    				String archiveId = matcher.group(1);
    				fileName = matcher.group(2);
    				filePath = "/uploads/archiveFile/"+archiveId+"/"+fileName;
    				System.out.println("filePath" + filePath);
    			}else{}
    		}
    		
    		
    		
            File file = new File(this.servletContext.getRealPath("/") + filePath);
            
            if(!file.exists()){
            	System.out.println("目标下载文件不存在");
            	ResponseStaticUtil.write(response, "目标下载文件不存在");
        		return null;
            }
            //response.sendRedirect(filePath);
            
            
            //头部设置文件类型
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
            //headers.setContentDispositionFormData("attachment", upload.getName());
    		if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {	//IE浏览器UTF-8
    			System.out.println("IE浏览器");
    			headers.setContentDispositionFormData("attachment", fileName);
    		}/*else if(request.getHeader("User-Agent").contains("Firefox")){	//火狐浏览器
    			fileName="=?utf-8?b?"+new BASE64Encoder().encode(fileName.getBytes("utf-8"))+"?=";
    		}*/else{	// 其他浏览器attachment;filename*=utf-8'zh_cn
    			System.out.println("其他浏览器");
    			response.setHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(fileName,"utf-8")+"");// 重点
    		}
            
            
    		//返回文件字节数组
            /*try {
                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
            } catch (IOException e) {
                e.printStackTrace();
                return null;    
            }*/
    		InputStream in = new FileInputStream(file);  
            OutputStream out = response.getOutputStream();  
            byte[] b = new byte[1024];
            int length = 0;
            while((length = in.read(b)) != -1)  {  
                out.write(b,0,length);  
            }  
            in.close();  
            out.close();
            return null;
        }

    有必要说一下,为什么没有使用FileUtils的readFileToByteArray方法,而是使用原始的out.write,因为前者在移动端中下载文件是不成功的(但奇怪的是在电脑端上却是正常的)。