`
huangyongxing310
  • 浏览: 481932 次
  • 性别: 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也...本软件非常的小,目的就一个,就是把邮箱里面尽可能多的邮件和附件弄到一个文件夹里面去。 如果不清楚怎么用,请看帮助,谢谢!

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

    资源不能上传demo图,亲测可用 datatable导出excel,并将附件复制到服务器临时目录,打包ZIP格式下载,临时目录删除。 导出需要引用NPOI.dll

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

    在notes端点击按钮开始对该视图的数据以excel形式进行导出,并将文档中的附件放置在以每个文档ID为文件夹的下面。本资源给出的是数据库文档,和说明该功能的Word文档。

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

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

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

    Java根据Url把多个文件下载到指定的文件夹目录,然后再将文件夹目录打包成zip导出,包括子目录也可以打包,有个简单的导出html页面,点击导出按钮下载zip。

    excel附件多sheet导出

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

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

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

    javaScript导出word和excel例子

    javaScript写的方法,将html导出word和excel的详细例子。

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

    保存任何文件和从数据库导出文件到本地磁盘,ACCESS文件,连接MSSQL

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

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

    人人网日志导出工具 20151002更新版

    近日人人网宣布站内信功能“死亡”,所以从网上找了Kaisir&Alin的人人网日志导出工具(2011年的代码),但是运行出错,修改后,经VS2013和Win7环境测试OK,特共享在此。 做的修改主要如下: 1)增加日志总数统计;...

    表格导出EXCEL含超链接的POI方式

    JAVA开发中需要将表格中数据导出成EXCEL文件,其中的某一项又要设置为HTML格式,并支持点击链接,使用POI的开源方式导出时可以参考到此文件的内容!

    Confluence 批量导出doc的shell脚本

    Confluence 批量导出doc的shell脚本,方便快捷,不用再自己去粘贴复制文档!

    easyPOI导出.rar

    easyPOI 导出,支持单个sheet页的数据导出(其中包括了附件图片的导出),支持多sheet页数据导出,支持动态数据表头的excle文件导出

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

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

    swagger导出静态API文档工具

    工具是一个maven工程,可通过maven命令导出静态接口文档,具体操作步骤见附件中的ReadMe.txt

    JAVA poi 做EXCEL导出(包含图片) 完整版

    需要使用JAVA 做EXCEL导出的同学,有问题尽管私信

    用Jxls导入导出Excel2003和Excel2007数据

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

    java导出jqgrid表格数据为excel

    前端页面点击导出jqgrid表格为excel表格代码,有表格样式设置的代码,可以参考一下,这是我刚开始工作的时候写的,希望可以帮助像我一样的菜鸟。

    微信备份导出精灵v1.123 全面支持安卓苹果手机+一键导出微信备份到电脑

    答:手机端接收查看成功的文件才可以正常导出,有些文件没有被下载,手机中本身就没有文件数据。 源码更新日志: V1.122 添加头像展示。 优化群成员昵称及头像的展示。 优化导出相关数据。 添加 6 小时授权模式。

Global site tag (gtag.js) - Google Analytics