`
huangyongxing310
  • 浏览: 490709 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

附件下载和导出

 
阅读更多
//post下载导出附件
function exportDetail() {
	var rows = grid.getSelecteds();
	if (rows.length > 0) {
		var ids = [];
		for (var i = 0, l = rows.length; i < l; i++) {
			ids.push('\''+rows[i].orderNo+'\'');
		}
		if(ids.length <= 0 ){
			return;//不需要提交后台
		}
		var id = ids.join(',');
		
		var url="/HIP/pmEntry/exportDetail.do";
		
		var params = {};
		params.orderNo = id;
		//params.value = id;
		post(url, params); 
		
		//location.href ="/HIP/pmEntry/exportDetail.do?orderNo="+id;
	} else {
		mini.alert("请选中要导出明细的记录");
	}
}


function post(url, params) { 
    // 创建form元素
    var temp_form = document.createElement("form");
    // 设置form属性
    temp_form .action = url;      
    temp_form .target = "_self";
    temp_form .method = "post";      
    temp_form .style.display = "none";
    // 处理需要传递的参数 
    for (var x in params) { 
        var opt = document.createElement("textarea");      
        opt.name = x;      
        opt.value = params[x];      
        temp_form .appendChild(opt);      
    }      
    document.body.appendChild(temp_form);
    // 提交表单      
    temp_form .submit();     
} 







GET方式
<a id="downButton2" class="mini-button" iconCls="icon-download" onclick="download()">下载附件</a>
 
 
 
 <iframe id="downloadfile" style="display: none"></iframe>
 
 
 
 //下载附件
	function download(){
		var iframe = document.getElementById("downloadfile");
		var rows = grid.getSelecteds()
		if(rows.length>0){
			if(rows.length>1){
				mini.alert("只能选择一条记录");
			}else{
				if(rows[0].pk!=null){
					var messageid = mini.loading("系统处理中,请稍后...", "系统处理中");
					setInterval("hideMessageBox('"+messageid+"')",2000);
					iframe.src = "${Download}?fileId="+rows[0].pk+"&type="+rows[0].type;
				}else{
					mini.alert("请上传附件");
				}
			}
			
		}else{
			mini.alert("请选择一条记录");
		}
	}










ajax
$.ajax({
  url: '<URL_TO_FILE>',
  success: function(data) {
    var blob=new Blob([data]);
    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(blob);
    link.download="<FILENAME_TO_SAVE_WITH_EXTENSION>";
    link.click();
  }
});










@RequestMapping (value="/downloadSalesReport")
    @ResponseBody
    public void downloadSalesReport( String id,HttpServletResponse response) throws  Exception {
    	BufferedInputStream in = null;  
        BufferedOutputStream out = null;  
        try {  
      
        	String fileName = "D:\\salesReportTest\\12345.xlsx";
        	String fileOutName = "测试salesReport.xlsx";
        	
        	fileOutName = new String(fileOutName.getBytes("UTF-8"), "ISO8859-1");
//        	action.setFilename(new String(fileName.getBytes("gbk"),"iso8859-1"));
        	
            File file = new File(fileName);  
            in = new BufferedInputStream(new FileInputStream(file));  
            out = new BufferedOutputStream(response.getOutputStream());  
            response.setContentType(new MimetypesFileTypeMap().getContentType(file));// 设置response内容的类型  
            response.setHeader("Content-disposition", "attachment;filename=" + fileOutName);// 设置头部信息  
            byte[] buffer = new byte[2048];  
            int length = 0;  
            while ((length = in.read(buffer)) > 0) {  
                out.write(buffer, 0, length);  
            }  
            out.flush();  
        } catch (IOException e) {  
        	 e.printStackTrace();
        } finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
                if (out != null) {  
                    out.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }




    @RequestMapping (value="/downloadSalesReport")
    @ResponseBody
    public void downloadSalesReport( String id,HttpServletResponse response) throws  Exception {
    	BufferedInputStream in = null;  
        BufferedOutputStream out = null;  
        try {  
      
        	String fileName = "D:\\salesReportTest\\12345.xlsx";
//        	/usr/HIP/dtomcat_MALL_pre/webapps/images/userfiles/policy
//        	02d40fb0864941798541850daef8d953.png
//        	File f = File.createTempFile(System.currentTimeMillis() + "_", ".downloadByIds");
//        	 FileOutputStream fo = new FileOutputStream(f);
        	
//        	if(id==null || id.equals("")) {
//        		throw new RuntimeException("id为空");
//        	}
//        	
//        	SalesReport salesReport = salesReportService.selectById(id);
//        	if(id==null || id.equals("")) {
//        		throw new RuntimeException(id + ":对应的数据不存在");
//        	}
//        	
//        	
//        	String fileOutName = salesReport.getFileName();
//        	if(fileOutName==null||fileOutName.equals("")) {
//        		throw new RuntimeException(id + ":对应的数据文件名为空");
//        	}
////        	String fileOutName = salesReport.getFileName();
        	
        	
        	
        	ftpService.downloadFile("/userfiles/policy/02d40fb0864941798541850daef8d953.png",response.getOutputStream());
        	

//        	String fileName = "D:\\salesReportTest\\12345.xlsx";
//        	String fileOutName = "测试salesReport.xlsx";
        	String fileOutName = "测试salesReport.png";
        	
        	fileOutName = new String(fileOutName.getBytes("UTF-8"), "ISO8859-1");
//        	action.setFilename(new String(fileName.getBytes("gbk"),"iso8859-1"));
        	
//            File file = new File(fileName);  
//            in = new BufferedInputStream(new FileInputStream(file));  
//            out = new BufferedOutputStream(response.getOutputStream());  
//            response.setContentType(new MimetypesFileTypeMap().getContentType(file));// 设置response内容的类型  
//            response.setContentType(MediaType.APPLICATION_OCTET_STREAM);// 设置response内容的类型  
            
            response.setHeader("Content-disposition", "attachment;filename=" + fileOutName);// 设置头部信息  
//            byte[] buffer = new byte[2048];  
//            int length = 0;  
//            while ((length = in.read(buffer)) > 0) {  
//                out.write(buffer, 0, length);  
//            }  
//            out.flush();  
        } catch (IOException e) {  
        	 e.printStackTrace();
        	 response.sendError(500, e.getMessage());
        } finally {  
            try {  
                if (in != null) {  
                    in.close();  
                }  
                if (out != null) {  
                    out.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }







	@RequestMapping(value = "/downloadSalesReport")
	@ResponseBody
	public void downloadSalesReport(String id, HttpServletRequest request,HttpServletResponse response) throws Exception {
//    	BufferedInputStream in = null;  
//        BufferedOutputStream out = null;  
		try {

//			if (id == null || id.equals("")) {
//				throw new RuntimeException("id为空");
//			}
//
//			SalesReport salesReport = salesReportService.selectById(id);
//			if (id == null || id.equals("")) {
//				throw new RuntimeException(id + ":对应的数据不存在");
//			}
//
//			String fileOutName = salesReport.getFileName();
//			if (fileOutName == null || fileOutName.equals("")) {
//				throw new RuntimeException(id + ":对应的数据文件名为空");
//			}
//
//			String folderName = salesReport.getFolderName();
//			if (folderName == null || folderName.equals("")) {
//				throw new RuntimeException(id + ":对应的数据文件路径为空");
//			}

			String fileOutName = "的数据文件dsd.png";
//			String fileName = folderName + "/" + fileOutName;
			String fileName = "/userfiles/policy/02d40fb0864941798541850daef8d953.png";

			ftpService.downloadFile(fileName, response.getOutputStream());
			
			//IE与chrome文件名乱码处理
			 String header = request.getHeader("User-Agent").toUpperCase();
		        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
		        	fileOutName = URLEncoder.encode(fileOutName, "utf-8");
		        	fileOutName = fileOutName.replace("+", "%20");    //IE下载文件名空格变+号问题
		        } else {
		        	fileOutName = new String(fileOutName.getBytes(), "ISO8859-1");
		        }
			
			response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=" + fileOutName);// 设置头部信息
  
		} catch (IOException e) {
			e.printStackTrace();
			response.sendError(500, e.getMessage());
		} 
	}










https://blog.csdn.net/dreaming317/article/details/82591600
https://blog.csdn.net/z69183787/article/details/80910606




https://blog.csdn.net/qq_30999361/article/details/84820420(在AJAX中发请求下载文件)




//=====================================ajax
<!DOCTYPE html>
<meta charset="utf-8" />
<HEAD>
<TITLE>网页即时提示演示</TITLE>
<!STYLE元素定义顶级元素BODY与行内元素SPAN的样式>

<!-- <script type="text/javascript" src="jquery.min.js"></script> -->

</HEAD>
<body>
	<button type="button" onclick="download()">导出</button>
</body>
<script type="text/javascript">
	function download() {
		var url = 'http://localhost:10080/downExport?filename=aaa.txt';
		var xhr = new XMLHttpRequest();
		xhr.open('GET', url, true); // 也可以使用POST方式,根据接口
		xhr.responseType = "blob"; // 返回类型blob
		// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
		xhr.onload = function() {
			// 请求完成
			if (this.status === 200) {
				var sucessFlag = xhr.getResponseHeader('sucessFlag')

				if (sucessFlag != 1) {
					var message = xhr.getResponseHeader('errorMessage');
					message = decodeURI(message);
					alert(message);
					return;
				}

				//====
				var fileName = xhr.getResponseHeader('fileName');
				if(fileName){
					fileName = decodeURI(fileName);
				}else{
					alert("下载文件名为空");
					return;
				}
				//====
				var blob = new Blob([ this.response ]);
				var link = document.createElement('a');
				link.href = window.URL.createObjectURL(blob);
				link.download = fileName;
				link.click();
			}
		};
		// 发送ajax请求
		xhr.send()
	}
</script>

</html>


package qg.fangrui.boot.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@RequestMapping("/downExport")
//@CrossOrigin
@RestController
public class downExportController {
	final static Logger logger = LogManager.getLogger(downExportController.class);

	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpServletResponse response;

	@RequestMapping(value = "/downExport")
	public void downExport() throws Exception {

		BufferedInputStream in = null;
		BufferedOutputStream out = null;
		try {
			// String fileName = "D:\\test002.pdf";
			// String fileOutName = "测试salesReport.pdf";

			// String fileName = "D:\\test003.png";
			// String fileOutName = "测试salesReport.png";

			// String fileName = "D:\\123456.xlsx";
			// String fileOutName = "测试salesReport.xlsx";
			//
			// String fileName = "D:\\副本.doc";
			// String fileOutName = "测试salesReport.doc";
			//
			String fileName = "D:\\副本11.doc";
			String fileOutName = "测试salesReport.doc";

			// IE与chrome文件名乱码处理
			// String header = request.getHeader("User-Agent").toUpperCase();
			// if (header.contains("MSIE") || header.contains("TRIDENT") ||
			// header.contains("EDGE")) {
			// fileOutName = URLEncoder.encode(fileOutName, "utf-8");
			// fileOutName = fileOutName.replace("+", "%20"); // IE下载文件名空格变+号问题
			// } else {
			// fileOutName = new String(fileOutName.getBytes(), "ISO8859-1");
			// }

			response.setContentType("text/html;charset=UTF-8");
			// response.setContentType("application/pdf");
			response.setHeader("Content-disposition", "attachment;filename=" + fileOutName);// 设置头部信息
			response.setHeader("sucessFlag", "1");// 设置头部信息
			response.setHeader("fileName", URLEncoder.encode(fileOutName, "UTF-8"));// 设置头部信息

			File file = new File(fileName);
			in = new BufferedInputStream(new FileInputStream(file));
			out = new BufferedOutputStream(response.getOutputStream());
			byte[] buffer = new byte[2048];
			int length = 0;
			while ((length = in.read(buffer)) > 0) {

				out.write(buffer, 0, length);
			}
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
			response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Content-disposition", "");// 设置头部信息
			response.setHeader("sucessFlag", "0");// 设置头部信息
			response.setHeader("errorMessage", URLEncoder.encode(e.getMessage(), "UTF-8"));// 设置头部信息
			response.getOutputStream().write(e.getMessage().getBytes());
		} finally {

			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}

		}
	}

}











//解决Response中文乱码问题
response.setContentType("text/html;charset=UTF-8");
			response.setHeader("Content-disposition", "");// 设置头部信息
			response.getOutputStream().write(e.getMessage().getBytes("UTF-8"));
			return null;






@PostMapping("/matMakeExport")
	@ApiOperation(value = "导出", notes = "导出", response = String.class)
	@ResponseBody
	public void matMakeExport(@RequestBody ExportParam param) throws Exception {
		LogUtils.info(param, "param");
		try {
			InputStream inputStream = MatMakeServiceImpl.matMakeExport(param);
			ExportUtils.HttpServletResponseExport(inputStream, response,"导出 .xls");
		} catch (Exception e) {
			e.printStackTrace();
			response.setHeader("downFileErrorMsg", ExceptionUtils.getExceptionTenLevel(e));// 设置头部信息
			response.sendError(200, "");
		} finally {
			
		}
	}




function ajaxDownFile(url, data,fileName) {
    commonConsole(url, "ajaxDownFile url");
    commonConsole(data, "ajaxDownFile data");
    var dataParam = getAjaxPostDataFormatParam(data);
    commonConsole(dataParam, "ajaxPost dataParam");

    request({
        url: url,
        method: 'post',
        data: dataParam,
        responseType: 'blob'
    }).then(result => {
        commonConsole(result, "ajaxDownFile result");
        var blob=new Blob([result]);

        commonConsole(blob, "ajaxDownFile blob");
        var link=document.createElement('a');
        link.href=window.URL.createObjectURL(blob);
        link.download=fileName;
        link.click();
    });
}



function ajaxDownFile(url, data, fileName) {
	commonConsole(url, "ajaxDownFile url");
	commonConsole(data, "ajaxDownFile data");
	var dataParam = data;
	// var dataParam = getAjaxPostDataFormatParam(data);
	commonConsole(dataParam, "ajaxPost dataParam");


	var url = url;
	var xhr = new XMLHttpRequest();
	xhr.open('POST', url, true); // 也可以使用POST方式,根据接口
	xhr.setRequestHeader('Content-type', 'application/json;charset=utf-8');
	xhr.responseType = "blob"; // 返回类型blob
	// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
	xhr.onload = function () {
		// 请求完成
		if (this.status != 200) {
			// var sucessFlag = xhr.getResponseHeader('sucessFlag');

			// if (sucessFlag != 1) {
				var message = xhr.getResponseHeader('errorMessage');
				message = decodeURI(message);
				commonConsole(message, "ajaxDownFile errorMessage");
				openAlert("文件下载失败,请联系管理员");
				return;
			// }
		}


		var blob = new Blob([this.response]);
		if ('msSaveOrOpenBlob' in navigator) {
			//ie使用的下载方式
			window.navigator.msSaveOrOpenBlob(blob, fileName);
		} else {
			commonConsole(blob, "ajaxDownFile blob");
			var link = document.createElement('a');
			link.href = window.URL.createObjectURL(blob);
			link.download = fileName;
			link.click();
		}
	};
	// 发送ajax请求
	xhr.send(JSON.stringify(dataParam));


}


分享到:
评论

相关推荐

    foxmail 附件批量导出

    中国Foxmail早已成为收发邮件的首选软件,其功能也早已超越Outlook,但是Foxmail也...本软件非常的小,目的就一个,就是把邮箱里面尽可能多的邮件和附件弄到一个文件夹里面去。 如果不清楚怎么用,请看帮助,谢谢!

    lotus domino附件开发--批量下载附件

    Lotus Domino 附件开发--批量下载附件 Lotus Domino 是 IBM 开发的一款企业级电子邮件客户端和协作平台,附件开发是其中的一个...通过使用 LotusScript 语言和 Windows API 函数,可以轻松地实现批量下载附件的功能。

    档案系统文档excel导出、将附件抛到本地

    档案系统文档Excel导出与附件抛到本地是一个常见的IT应用场景,尤其在企业级的信息管理和办公自动化系统中。这里主要涉及的技术点包括 Domino Lotus 数据库、Excel 导出、以及附件管理。 1. **Domino Lotus 数据库*...

    asp.net mvc导出excel附件打包下载

    在ASP.NET MVC框架中,有时候我们需要为用户提供一个功能,让他们能够导出数据为Excel格式,并且将相关的附件一并打包成ZIP文件进行下载。这个功能通常用于数据分析、报告生成或者数据备份等场景。下面我们将详细...

    Java多个文件根据URL下载后打包zip导出.zip

    5. **事件处理与异步操作**:为了提供更好的用户体验,下载和打包过程可能需要异步执行,避免阻塞主线程。Java 8引入了`CompletableFuture`,可以方便地处理异步任务和回调。此外,Spring框架提供了`...

    javaScript导出word和excel例子

    这对于数据导出、报告生成或者网页内容下载等场景非常有用。以下是对标题和描述中涉及知识点的详细说明: 1. **JavaScript基础**: JavaScript是一种广泛应用于网页和网络应用的脚本语言,它在浏览器环境中运行,...

    excel附件多sheet导出

    在项目过程中需要突然要求支持导出多个sheet的excel附件信息。并且每个sheet中的字段都不一样。 目前的解决方案是 通过配置execl的格式,在后台通过java反射机制动态生成导出对象的方式实现。 上传了源代码,但是...

    lotus domino附件开发--附件批量放到一个文档

    Lotus Domino 附件开发是指使用 Lotus Domino 提供的 API 和开发工具来创建、管理和处理附件的过程。Lotus Domino 提供了强大的附件处理功能,允许开发者创建、读取、修改和删除附件。 在我们的示例代码中,我们...

    asp.net+Ajax实现Excel文件导出

    通过以上步骤,我们就能在ASP.NET和Ajax的帮助下,实现Excel文件的无缝导出。这个功能对于需要频繁导出数据的Web应用来说非常实用,同时也提升了用户体验,因为用户可以在不离开当前页面的情况下完成导出操作。

    PDF模板报表导出,所需要的附件

    在这个场景中,"PDF模板报表导出,所需要的附件" 提供了几个关键元素,让我们来深入探讨这些知识点。 1. **PDF(Portable Document Format)**:PDF是一种通用的文件格式,它能够保持文档的原始布局和样式,使得在...

    java导出excel(写入到excel后再下载)示例

    同时,设置合适的HTTP头如"Content-Disposition",以指示浏览器将内容作为附件下载,例如`response.setHeader("Content-Disposition", "attachment; filename=export.xls")`。 在提供的压缩包`excelweb`中,可能...

    保存任何文件和从数据库导出文件到本地磁盘

    在IT领域,保存文件和从数据库导出文件到本地磁盘是常见的操作,尤其是在软件开发中。本主题主要涉及文件操作、数据库交互以及C#编程语言的应用。以下将详细阐述这些知识点。 首先,文件操作是计算机编程的基础。在...

    Struts2文件流方式导出下载excel、Txt、image图片

    在实际项目中,我们经常需要提供文件下载功能,比如导出Excel表格、文本文件或者图片。Struts2提供了文件流的方式来实现这一需求,这种方式避免了在服务器上生成临时文件,提高了效率并减少了服务器存储空间的占用。...

    C#读取.eml文件(带附件下载)

    本文将深入探讨如何使用C#语言来读取并处理`.eml`文件,特别是如何在`.eml`文件中查找并下载附件。`.eml`文件是一种标准格式,用于存储电子邮件消息,包括其内容、主题、发送者、接收者以及可能的附件。 首先,我们...

    文件的上传与下载,excel表的导入与导出

    在IT领域,文件的上传与下载,以及Excel表的导入与导出是常见的操作,尤其在Web应用、数据分析和信息管理中。以下是对这些概念的详细解释和实践中的应用。 **文件上传**: 文件上传是指将本地计算机上的文件通过...

    java poi导出excel,弹窗提示下载

    filename=yourfile.xls"或".xlsx",这将告诉浏览器以附件形式下载文件。 8. **关闭资源**: 导出完成后,记得关闭Workbook和OutputStream,释放资源。 在提供的压缩包"day3(SSH框架)"中,可能包含了一个使用...

    destoon添加数据导出到excel表格中.doc

    最后,通过 HTTP 头部信息告诉浏览器将以附件的形式下载名为 "export_data.xlsx" 的文件,并直接输出到浏览器。 在实际操作中,你可能还需要考虑一些额外的细节,比如错误处理、数据过滤、导出格式定制(日期格式、...

    Python-confluencedumper通过API能递归样的将Confluence空间和页页都导出

    这种递归方式确保了所有子页面和附件都能被正确地捕获和导出。 1. **Confluence REST API**:Confluence提供了一套全面的API,允许开发者使用HTTP请求进行读写操作。这些API包括获取空间信息、页面内容、版本历史、...

    金蝶K3附件转存储工具

    4. **权限管理**:支持设置不同的访问权限,控制不同用户对附件的查看和下载,保证数据的安全性。 5. **优化存储**:通过智能压缩和去重技术,减少存储空间的占用,提高存储效率。 在使用金蝶K3附件转存储工具之前...

    用Jxls导入导出Excel2003和Excel2007数据2

    用Jxls和Excel可以做出完美的报表,简洁高效,而且可以方便地处理Excel的数据,对于Java应用来说,实为上上之选!...本人经过反复调试,最后配出正确的系列jar文件,包括源码都在附件中,欢迎大家下载!

Global site tag (gtag.js) - Google Analytics