1. MySQL
1 public void getFile(String id,HttpServletResponse response) { 2 // TODO 自动生成的方法存根 3 DataObject criteria = DataFactory.INSTANCE.create("com.primeton.das.criteria", "criteriaType"); 4 criteria.set("_entity", "com.primeton.eos.auditManager.audit.service.audit.AuditFiles"); 5 criteria.set("_expr[1]/fileId", id); 6 DataObject[] datas = DatabaseUtil.queryEntitiesByCriteriaEntity("default", criteria,0,1); 7 if(datas.length > 0) { 8 String fileName = datas[0].getString("fileName"); 9 response.reset(); // 清除buffer缓存 10 response.setCharacterEncoding("UTF-8"); 11 try { 12 response.addHeader("Content-Disposition",String.format("attachment; filename=\"%s\"", URLEncoder.encode(fileName, "utf-8"))); 13 //datas[0] 取出当前的实体信息,getBytes为返回byte数组数据,塞进response中返回给前台 response.getOutputStream().write(datas[0].getBytes("content")); 14 } catch (IOException e) { 15 // TODO 自动生成的 catch 块 16 e.printStackTrace(); 17 } 18 } 19 }
2. MongoDB
1 public void getFile(String id, HttpServletResponse response) { 2 GridFS gridFs = new GridFS(MongodbUtil.getDB(), "files"); 3 GridFSDBFile gfsfile = gridFs.findOne(new BasicDBObject("_id", id)); 4 if (gfsfile == null) { 5 return; 6 } 7 String fileName = gfsfile.getFilename().replace(",", ""); 8 response.reset(); // 清除buffer缓存 9 response.setCharacterEncoding("UTF-8"); 10 response.setContentType(gfsfile.getContentType()); 11 try { 12 response.setContentType("application/x-download"); 13 response.addHeader("Content-Disposition",String.format("attachment; filename=\"%s\"", URLEncoder.encode(fileName, "utf-8"))); 14 //将文件数据流塞进response中 15 gfsfile.writeTo(response.getOutputStream()); 16 } catch (IOException e) { 17 // TODO 自动生成的 catch 块 18 e.printStackTrace(); 19 } 20 }
3. OSS
1 //END_POIND, ACCESS_KEY_ID,ACCESS_KEY_SECRET,BUCKET_NAME为OSS第三方提供的唯一串 2 public void getFile(String id, HttpServletResponse response) { 3 4 OSS ossClient = null; 5 try { 6 ossClient = new OSSClientBuilder().build(END_POIND, ACCESS_KEY_ID,ACCESS_KEY_SECRET); 7 OSSObject ossObject = ossClient.getObject(BUCKET_NAME, id); 8 response.reset(); // 清除buffer缓存 9 response.setCharacterEncoding("UTF-8"); 10 response.addHeader("Content-Disposition",String.format("attachment; filename=\"%s\"", URLEncoder.encode("文件", "utf-8"))); 11 response.getOutputStream().write(toByteArray(ossObject.getObjectContent())); 12 ossObject.close(); 13 } catch (Exception e) { 14 log.error("文件下载发生异常错误",e); 15 return; 16 }finally { 17 if(ossClient!=null) { 18 ossClient.shutdown(); 19 } 20 21 } 22 } 23 //文件流转byte数组 24 private byte[] toByteArray(InputStream input) throws IOException { 25 ByteArrayOutputStream output = new ByteArrayOutputStream(); 26 byte[] buffer = new byte[1024 * 4]; 27 int n = 0; 28 while (-1 != (n = input.read(buffer))) { 29 output.write(buffer, 0, n); 30 } 31 return output.toByteArray(); 32 }