response 中OutputStream和PrintWriter区别

https://blog.csdn.net/feipeng8848/article/details/56286399

https://blog.csdn.net/lhanson/article/details/83893999

https://blog.csdn.net/qq_16605855/article/details/78260355

public class RenderUtil {

    /**
     * 渲染json对象
     */
    public static void renderJson(HttpServletResponse response, Object jsonObject) {
        try {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(jsonObject));
        } catch (IOException e) {
            throw new MsApiException("响应异常",1);
        }
    }
}

	/**
	 * 模板下载
	 * 
	 * @param name
	 */
	@ApiOperation(value = "模板下载", notes = "模板下载")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", dataType = "String", name = "id", value = "主键", required = true) })
	@GetMapping(value = "/downloadtemplate")
	public void downLoadTemplate(@RequestParam(value = "id", required = true) String id, HttpServletResponse response,
			HttpServletRequest request) {
		try {
			TemplateInfo templateInfo = this.iTemplateInfoService.getById(id);
			if (templateInfo != null) {
				String parentDir = null;
				try {
					parentDir = this.getClass().getClassLoader().getResource("").getPath();
				} catch (Exception e) {
					log.error("读取根路径报错", e);
				}
				String path = parentDir + templateInfo.getTemplateUrl();
				String fileName = templateInfo.getName() + ".xlsx";
				String userAgent = request.getHeader("USER-AGENT");
				if (StringUtils.contains(userAgent, "MSIE")) {// IE浏览器
					fileName = URLEncoder.encode(fileName, "UTF8");
				} else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
					fileName = new String(fileName.getBytes(), "ISO8859-1");
				} else {
					fileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
				}
				// 以流的形式下载文件。
				InputStream fis = new BufferedInputStream(new FileInputStream(path));
				// 清空response
				response.reset();
				// 设置response的Header
				response.setCharacterEncoding("UTF-8");
				response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
				response.addHeader("Content-Length", "" + fis.available());
				response.setContentType("application/octet-stream");
				int len = 0;
				byte[] buffer = new byte[1024];
				OutputStream out = response.getOutputStream();
				while ((len = fis.read(buffer)) > 0) {
					// 将缓冲区的数据输出到客户端浏览器
					out.write(buffer, 0, len);
				}
				fis.close();
				out.flush();
				out.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	/**
	 * excel导入
	 * 
	 * @param file
	 * @param response
	 */
	@ApiOperation(value = "excel导入", notes = "excel导入")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "file", value = "单个文件", paramType = "formData", required = true, dataType = "file"),
			@ApiImplicitParam(name = "id", value = "id", paramType = "query", required = true, dataType = "String") })
	@PostMapping(value = "/exporttemplate", headers = "content-type=multipart/form-data")
	public void exportTemplate(@RequestParam(value = "id", required = true) String id,
			@RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// 一.使用EasyPoi获取文件数据
			ImportParams params = new ImportParams();
			params.setHeadRows(1);
			params.setNeedVerfiy(true); // 设置验证支持
			// 二.获取excel中的数据,封装成了一个结果对象(有很多东西)
			ExcelImportResult<ImportStreetTypeVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(),
					ImportStreetTypeVO.class, params);
			// 三.获到正确的数据,并把它们保存到数据库
			List<ImportStreetTypeVO> list = result.getList();
			List<PeopleBy> peopleByList = Lists.newLinkedList();
			if (CollectionUtils.isNotEmpty(list)) {
				list.forEach(e -> {
					PeopleBy peopleBy = new PeopleBy();
					try {
						BeanUtils.copyProperties(e, peopleBy);
					} catch (IllegalAccessException e1) {
						e1.printStackTrace();
					} catch (InvocationTargetException e1) {
						e1.printStackTrace();
					}
					peopleBy.setCreated(new Date());
					if (Integer.valueOf(id) == 1) {
						peopleBy.setByRType(5);
					} else if (Integer.valueOf(id) == 2) {
						peopleBy.setByRType(4);
					}
					peopleByList.add(peopleBy);
				});
				this.iPeopleByService.saveBatch(peopleByList);
			}

			// 四.如果有错误,把错误数据返回到前台(让前台下载一个错误的excel)
			// 4.1判断是否有错误
			if (result.isVerfiyFail()) {
				// 4.2拿到错误的文件薄
				Workbook failWorkbook = result.getFailWorkbook();
				// 把这个文件导出
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // mime类型
				response.setHeader("Content-disposition", "attachment;filename=error.xlsx"); // 告诉浏览下载的是一个附件,名字叫做error.xlsx
				response.setHeader("Pragma", "No-cache");// 设置不要缓存
				OutputStream ouputStream = response.getOutputStream();
				failWorkbook.write(ouputStream);
				ouputStream.flush();
				ouputStream.close();
			}
		} catch (Exception e) {
			log.error("excel导入出错", e);
		}
	}
	/**
	 * 从阿里云下载附件
	 * 
	 * @author ljj
	 * @param response
	 * @param request
	 */
	@ResponseBody
	@RequestMapping(value = "/downloadFromOss", method = RequestMethod.GET)
	public void downloadFromOss(HttpServletResponse response, HttpServletRequest request) {
		try {
			String fileid = request.getParameter("id");
			if (StringUtils.isBlank(fileid)) {
				return;
			}
			// 记录下载日志
			WebBaseContext webBaseContext = WebBaseUtils.getBaseContext();
			SecurityUserDetails securityUserDetails = webBaseContext.getSecurityUserDetails();
			fileOpatatorLogService.recordDownloadFileOparatorLog("", "", fileid,
					securityUserDetails == null ? "" : securityUserDetails.getUserAccount());
			List<Map<String, Object>> fileList = this.iOrganizationBizc.queryFileInfoByFileId(fileid);
			if (fileList.isEmpty()) {
				response.sendRedirect(request.getContextPath() + "/405.jsp");
				return;
			}
			String fileStr = "";
			String ossfilekey = "";
			if (fileList.size() > 0) {
				fileStr = fileList.get(0).get("NAME") + "." + fileList.get(0).get("FILE_TYPE");
				ossfilekey = XfxtUtils.getMapString(fileList.get(0), "STOR_ADDR");
			}
			String aliyunId = ApplicationPropertyUtils.getContextProperty("ALIYUN_ACCESS_KEY_ID");
			String aliyunSecret = ApplicationPropertyUtils.getContextProperty("ALIYUN_ACCESS_KEY_SECRET");
			String ossEndpoint = ApplicationPropertyUtils.getContextProperty("ALIYUN_OSS_ENDPOINT");
			response.reset();
			setExportHeader(request, response, fileStr, 2);
			
			OSSClient ossClient = new OSSClient(ossEndpoint, aliyunId, aliyunSecret);
			// 获取fileid对应的阿里云上的文件对象
			OSSObject ossObject = ossClient.getObject(ApplicationPropertyUtils.getContextProperty("ALIYUN_OSS_BUCKET"),ossfilekey);// bucketName需要自己设置
			// 读去Object内容 返回
			BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			
			byte[] car = new byte[1024];
			int l = 0;
			while ((l = in.read(car)) != -1) {
				out.write(car, 0, l);
			}
			if (out != null) {
				out.flush();
				out.close();
			}
			if (in != null) {
				in.close();
			}
			ossClient.shutdown();
		} catch (OSSException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置导出文件名乱码问题
	 * @Title: setExportHeader   
	 * @param: @param request request请求信息
	 * @param: @param response response返回信息
	 * @param: @param fileName 文件名称
	 * @param: @param type  文件类型 1 excel
	 * @author: lijiwei 
	 * @date:   2017年11月7日 下午8:04:18
	 */
	public static void setExportHeader(HttpServletRequest request, HttpServletResponse response, String fileName, int type){
		try{
			String contentType = null;
			
			switch (type) {
			case 1:
				contentType = "application/msexcel;";
				break;
			case 2:
				contentType = "application/octet-stream;";
				break;
			default:
				contentType = "application/msexcel;";
				break;
			}
			
			response.setContentType(contentType+"charset=UTF-8");
			
			
			String userAgent = request.getHeader("User-Agent").toLowerCase();
			if (userAgent.indexOf("firefox") > 0) {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
			} else if (userAgent.indexOf("msie") > 0 || userAgent.indexOf("trident") > 0 || userAgent.indexOf("edge") > 0) {
				fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
			} else if (userAgent.indexOf("chrome") > 0) {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// 谷歌
			} else {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
			}
			response.setHeader("Content-Disposition","attachment;" + " filename=" + fileName);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
package com.awj.mall.modular.down.controller;

import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.awj.mall.core.base.controller.BaseController;
import com.awj.mall.core.util.OssClientFactory;
import com.awj.mall.modular.goods.model.GoodsLib;
import com.awj.mall.modular.goods.service.IGoodsLibService;

/**
 * 
 * @author ljj 文件从oss批量下载zip
 *
 */
@Controller
@RequestMapping("/ossdownload")
public class OssDownLoadController extends BaseController {

	@Resource
	private IGoodsLibService iGoodsLibService;

	private Log log = LogFactory.getLog(this.getClass());

	@RequestMapping(value = "/ossdownloadtozip", method = RequestMethod.GET)
	public void ossDownLoadToZip(String goodsId, HttpServletResponse response, HttpServletRequest request) {
		GoodsLib goodsLib = this.iGoodsLibService.selectById(goodsId);
		Map<String, InputStream> fileMap = new LinkedHashMap<String, InputStream>();
		if (goodsLib != null) {
			String goodsFile = goodsLib.getGoodsFile();
			if (StringUtils.isNotBlank(goodsFile)) {
				List<FileObject> fileObjects = null;
				try {
					fileObjects = JSONArray.parseArray(goodsFile, FileObject.class);
				} catch (Exception e) {

				}
				OSSClient ossClient = OssClientFactory.getOssClient();
				if (fileObjects != null) {
					fileObjects.forEach(fileObject -> {
						String value = fileObject.getValue();
						String name = fileObject.getName();
						int fileIndex = value.indexOf(OssClientFactory.endpointchange)
								+ OssClientFactory.endpointchange.length() + 1;
						// 获取fileid对应的阿里云上的文件对象
						OSSObject ossObject = ossClient.getObject(OssClientFactory.bucketName,
								value.substring(fileIndex));// bucketName需要自己设置
						// 读去Object内容 返回
						fileMap.put(name, ossObject.getObjectContent());
					});

				}

			}

		}
		try {
			// 03:开始将下载下来的文件流,写入到压缩包中,并使用浏览器方式下载:
			String downloadZipFileName = "产品附件.zip"; // 压缩包名字:
			ZipOutputStream out = new ZipOutputStream(response.getOutputStream());// --设置成这样可以不用保存在本地,再输出,
																					// 通过response流输出,直接输出到客户端浏览器中。
			if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
				downloadZipFileName = new String(downloadZipFileName.getBytes("GB2312"), "ISO-8859-1");
			} else {
				// 对压缩包文件名进行编码处理中文问题
				downloadZipFileName = java.net.URLEncoder.encode(downloadZipFileName, "UTF-8");
				downloadZipFileName = new String(downloadZipFileName.getBytes("UTF-8"), "GBK");
			}
			response.reset(); // 重点突出
			response.setCharacterEncoding("UTF-8"); // 重点突出
			response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出
			// 设置下载方式:
			// inline : 在浏览器中直接显示,不提示用户下载; -- 默认为inline方式
			// attachment : 弹出对话框,提示用户进行下载保存本地
			response.setHeader("Content-Disposition", "attachment;filename=" + downloadZipFileName);
			for (Map.Entry<String, InputStream> entry : fileMap.entrySet()) {
				// 文件名:
				String fileName = entry.getKey();
				// 文件流:
				InputStream in = entry.getValue();
				out.putNextEntry(new ZipEntry(fileName));
				int len;
				byte[] buf = new byte[4096];
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				in.close();
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("压缩成zip失败", e);
		}

	}

	static class FileObject {

		private String value;

		private String name;

		public String getValue() {
			return value;
		}

		public void setValue(String value) {
			this.value = value;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

	}

}

try {
            logger.info("【BillCommonFileServiceImpl】 download ==begin "+filePath);
            final String aliUrl="";//访问oss上文件的http://*。。。。aliyuncs.com/需要替换掉  直接是
            filePath=filePath.replaceAll(aliUrl,"");
            String[] split = filePath.split("/");
            String fileName= URLDecoder.decode(split[split.length-1],"UTF-8");//阿里的key值  utf8
            // 从阿里云进行下载
            //bucketName需要自己设置
            OSSClient client =createOSSClient();
            OSSObject ossObject = client.getObject(aliyunOSSConfig.getBucket(),filePath);
            // 已缓冲的方式从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));

            InputStream inputStream = ossObject.getObjectContent();

            //缓冲文件输出流
            BufferedOutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            // response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
            // 为防止 文件名出现乱码
            response.setContentType("application/doc");
            final String userAgent = request.getHeader("USER-AGENT");
            if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
                fileName = URLEncoder.encode(fileName,"UTF-8");
            }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            }else{
                fileName = URLEncoder.encode(fileName,"UTF-8");//其他浏览器
            }
            response.addHeader("Content-Disposition", "attachment;filename=" +fileName);//这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开
            logger.info("【BillCommonFileServiceImpl】 download ==end "+filePath);

            // 进行解码 如果上传时为了防止乱码 进行解码使用此方法
            BASE64Decoder base64Decoder = new BASE64Decoder();
//            byte[] car;
//            while (true) {
//                String line = reader.readLine();
//                if (line == null) break;
//                car =  base64Decoder.decodeBuffer(line);
//
//                outputStream.write(car);
//            }
//            reader.close();

            byte[] car = new byte[1024];
            int L;

            while((L = inputStream.read(car)) != -1){
                if (car.length!=0){
                    outputStream.write(car, 0,L);
                }
            }

            if(outputStream!=null){
                outputStream.flush();
                outputStream.close();
            }
            if (client !=null){
                client.shutdown();
            }

        } catch (IOException e) {
            logger.error("【BillCommonFileServiceImpl】 download ==IOException "+e.getMessage());
            e.printStackTrace();

        } catch (OSSException e){
            logger.error("【BillCommonFileServiceImpl】 download ==OSSException "+e.getMessage());
        }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值