response 中OutputStream和PrintWriter区别
生活随笔
收集整理的這篇文章主要介紹了
response 中OutputStream和PrintWriter区别
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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對(duì)象*/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("響應(yīng)異常",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("讀取根路徑報(bào)錯(cuò)", 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));// 清空responseresponse.reset();// 設(shè)置response的Headerresponse.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) {// 將緩沖區(qū)的數(shù)據(jù)輸出到客戶端瀏覽器out.write(buffer, 0, len);}fis.close();out.flush();out.close();}} catch (Exception ex) {ex.printStackTrace();}}/*** excel導(dǎo)入* * @param file* @param response*/@ApiOperation(value = "excel導(dǎo)入", notes = "excel導(dǎo)入")@ApiImplicitParams({@ApiImplicitParam(name = "file", value = "單個(gè)文件", 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獲取文件數(shù)據(jù)ImportParams params = new ImportParams();params.setHeadRows(1);params.setNeedVerfiy(true); // 設(shè)置驗(yàn)證支持// 二.獲取excel中的數(shù)據(jù),封裝成了一個(gè)結(jié)果對(duì)象(有很多東西)ExcelImportResult<ImportStreetTypeVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(),ImportStreetTypeVO.class, params);// 三.獲到正確的數(shù)據(jù),并把它們保存到數(shù)據(jù)庫(kù)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);}// 四.如果有錯(cuò)誤,把錯(cuò)誤數(shù)據(jù)返回到前臺(tái)(讓前臺(tái)下載一個(gè)錯(cuò)誤的excel)// 4.1判斷是否有錯(cuò)誤if (result.isVerfiyFail()) {// 4.2拿到錯(cuò)誤的文件薄Workbook failWorkbook = result.getFailWorkbook();// 把這個(gè)文件導(dǎo)出response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // mime類型response.setHeader("Content-disposition", "attachment;filename=error.xlsx"); // 告訴瀏覽下載的是一個(gè)附件,名字叫做error.xlsxresponse.setHeader("Pragma", "No-cache");// 設(shè)置不要緩存OutputStream ouputStream = response.getOutputStream();failWorkbook.write(ouputStream);ouputStream.flush();ouputStream.close();}} catch (Exception e) {log.error("excel導(dǎo)入出錯(cuò)", 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;}// 記錄下載日志W(wǎng)ebBaseContext 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對(duì)應(yīng)的阿里云上的文件對(duì)象OSSObject ossObject = ossClient.getObject(ApplicationPropertyUtils.getContextProperty("ALIYUN_OSS_BUCKET"),ossfilekey);// bucketName需要自己設(shè)置// 讀去Object內(nèi)容 返回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();}}/*** 設(shè)置導(dǎo)出文件名亂碼問(wèn)題* @Title: setExportHeader * @param: @param request request請(qǐng)求信息* @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 {@Resourceprivate 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對(duì)應(yīng)的阿里云上的文件對(duì)象OSSObject ossObject = ossClient.getObject(OssClientFactory.bucketName,value.substring(fileIndex));// bucketName需要自己設(shè)置// 讀去Object內(nèi)容 返回fileMap.put(name, ossObject.getObjectContent());});}}}try {// 03:開(kāi)始將下載下來(lái)的文件流,寫入到壓縮包中,并使用瀏覽器方式下載:String downloadZipFileName = "產(chǎn)品附件.zip"; // 壓縮包名字:ZipOutputStream out = new ZipOutputStream(response.getOutputStream());// --設(shè)置成這樣可以不用保存在本地,再輸出,// 通過(guò)response流輸出,直接輸出到客戶端瀏覽器中。if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {downloadZipFileName = new String(downloadZipFileName.getBytes("GB2312"), "ISO-8859-1");} else {// 對(duì)壓縮包文件名進(jìn)行編碼處理中文問(wèn)題downloadZipFileName = java.net.URLEncoder.encode(downloadZipFileName, "UTF-8");downloadZipFileName = new String(downloadZipFileName.getBytes("UTF-8"), "GBK");}response.reset(); // 重點(diǎn)突出response.setCharacterEncoding("UTF-8"); // 重點(diǎn)突出response.setContentType("application/x-msdownload");// 不同類型的文件對(duì)應(yīng)不同的MIME類型 // 重點(diǎn)突出// 設(shè)置下載方式:// inline : 在瀏覽器中直接顯示,不提示用戶下載; -- 默認(rèn)為inline方式// attachment : 彈出對(duì)話框,提示用戶進(jìn)行下載保存本地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="";//訪問(wèn)oss上文件的http://*。。。。aliyuncs.com/需要替換掉 直接是filePath=filePath.replaceAll(aliUrl,"");String[] split = filePath.split("/");String fileName= URLDecoder.decode(split[split.length-1],"UTF-8");//阿里的key值 utf8// 從阿里云進(jìn)行下載//bucketName需要自己設(shè)置OSSClient client =createOSSClient();OSSObject ossObject = client.getObject(aliyunOSSConfig.getBucket(),filePath);// 已緩沖的方式從字符輸入流中讀取文本,緩沖各個(gè)字符,從而提供字符、數(shù)組和行的高效讀取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"));// 為防止 文件名出現(xiàn)亂碼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);//這里設(shè)置一下讓瀏覽器彈出下載提示框,而不是直接在瀏覽器中打開(kāi)logger.info("【BillCommonFileServiceImpl】 download ==end "+filePath);// 進(jìn)行解碼 如果上傳時(shí)為了防止亂碼 進(jìn)行解碼使用此方法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());}總結(jié)
以上是生活随笔為你收集整理的response 中OutputStream和PrintWriter区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 中国省市区县级行政区划shapefile
- 下一篇: vscode 英伟达tk1_英伟达的未来