admin管理员组

文章数量:1533887

前台提交请求,到后台获取需要下载的文件生产流下载文件时, 浏览器端没有生产对应的文件,只获取了文件流。

再网上搜了一圈, 很多说在java端需要对response.setContentType() 进行设置, 但是我设置完成后依然 没有效果。 

到不是此设置无效, 而是问题出在提交请求的方式。

如果是通过流的方式下载文件时,提交方式必须为 http请求,而不能是ajax请求。 

具体代码:

 前台js部分

// 根据业务编号下载附件  使用form提交
        function downLaodFiles(scode){        
        // 路径
        var urlStr1 ="${base}/deliveryplanSupplierSell!downLoadFilesBySellCode.dhtml?sellcode="+scode;
        //form提交下载
		var form = $('<form></form>');     
		form.attr('style', 'display:none');      
		form.attr('target', '_blank');      
		form.attr('method', 'post'); //form提交路径      
		form.attr('action', urlStr1)
		var input = $('<input type="text" name="params" id="params" />'); // 可以添加一些参数            
		input.attr('value', scode);
		form.append(input); 
		$(document.body).append(form);
		form.submit();               

	      	 
       } 
        
       
     

后台java代码:


/**
	 * @version 1.0
	 * @Classname downLoadFilesBySellCode
	 * @description 根据业务编号从webservice获取下载文件
	 * @author 吴文进
	 * @throws IOException 
	 * @date 2017年2月17日09:56:00
	 */
	@SuppressWarnings("unused")
	public String downLoadFilesBySellCode() throws IOException{
		// 业务编号
		String sellcode = request.getParameter("sellcode");
		// 调用webservice 接口,获取需要下载的附件信息
		List<String> urlList = getDownLoadUrlByWebservice(sellcode);
		// 以流的形式下载文件
		ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
		// 获取邮件名称用作下载压缩包名称
		String zipName = sellcode+".zip";
        try {  
            response.setContentType("application/octet-stream");  
            String userAgent = request.getHeader("User-Agent").toLowerCase();  
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipName, "utf-8"));  
            // 保存所有附件名称, 用于判断下载附件名称是否重复, 防止打包时出错。
            String fileNames = "";
            // 重复数
            int cNum = 0 ;
            for (int i = 0; i < urlList.size(); i++) {
            	/*// 转换前文件名
            	String fileName = urlList.get(i).substring(urlList.get(i).lastIndexOf("/")+1, urlList.get(i).length());
            	// 路径名
            	String pathName = urlList.get(i).substring(0,urlList.get(i).lastIndexOf("/")+1);
            	// 处理路径名中的空格
            	pathName = pathName.replace(" ", "%20");
            	String newFileName = "";
            	try {
            		newFileName = URLEncoder.encode(fileName,"UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block 
					e.printStackTrace();
				}
            	newFileName = newFileName.replace("+", "%20");
            	URL url = new URL(pathName+newFileName);*/
            	URL url = new URL(urlList.get(i));
                HttpURLConnection conn = (HttpURLConnection)url.openConnection();      
                //设置超时间为3秒    
                conn.setConnectTimeout(60*1000);    
                //防止屏蔽程序抓取而返回403错误    
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");    
                //得到输入流    
                InputStream inputStream = conn.getInputStream(); 
                
                // 如果重复, 则名称后面添加(1)
               /* if(fileNames.contains(fileName)){
                	String fileType = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
                	String name = fileName.substring(0,fileName.lastIndexOf("."));
                	fileName = name + "("+ ++cNum +")." +fileType;
                }
                fileNames += fileName +",";*/
               // 将单个文件放进压缩包中
                //tempName=tempName.replace("%20"," ");
             // 附件名
                String tempName = urlList.get(i).substring(urlList.get(i).lastIndexOf("/")+1, urlList.get(i).length());
                if(fileNames.contains(tempName)){
                	String fileType = tempName.substring(tempName.lastIndexOf(".")+1,tempName.length());
                	String name = tempName.substring(0,tempName.lastIndexOf("."));
                	tempName = name + "("+ ++cNum +")." +fileType;
                }
                fileNames += tempName +",";
                zos.putNextEntry(new ZipEntry(tempName));     
				byte[] buffer = new byte[1024];     
				int r = 0;     
				while ((r = inputStream.read(buffer)) != -1) {     
					zos.write(buffer, 0, r);     
				}     
				inputStream.close(); 
			}
            zos.flush();     
		    zos.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
        } 
        return null;
	}


 

该代码下载为下载多个文件时,打包为一个压缩包下载,如果压缩包中的附件名称有重复的则在名称后面添加(1)(2)。。。。


   

本文标签: 文件数据流浏览器Java