REST
@RequestMapping(value = "/obtenerDocumentoPdf", method = RequestMethod.POST)
public void obtenerDocumentoPdf(HttpServletResponse response, @RequestParam Integer idDocumento,
@RequestParam String idCompania, @RequestBody Map<String, Object> body) throws IOException {
UsuarioActual usuario = new ObjectMapper().convertValue(body.get("usuario"),
new TypeReference<UsuarioActual>() {
});
DtoDocumento documento = consulta.obtenerDocumentoPdf(usuario, idCompania, idDocumento);
if (documento.getFlgEncontrado()) {
File file = new File(documento.getRutaCompleta());
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
if (mimeType == null) {
System.out.println("mimetype is not detectable, will take default");
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setHeader("Content-Disposition", String.format("attachment; filename=\"" + file.getName() + "\""));
response.setContentLength((int) file.length());
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
FileCopyUtils.copy(inputStream, response.getOutputStream());
}
}
ANGULAR
obtenerDocumentoPdf(idDocumento: number, idCompania: string, usuario: UsuarioActual) { const params = new URLSearchParams(); params.set("idDocumento", JSON.stringify(idDocumento * 1)); params.set("idCompania", idCompania); usuario.sidCliente = this.sid; return this.http.post(`${this.url}obtenerDocumentoPdf`, JSON.stringify({ usuario: usuario }), { responseType: ResponseContentType.Blob, search: params, headers: this.headers }) .map(res => { return { filename: 'filename.pdf', data: res.blob() }; }) .subscribe( (res) => { console.log('start download:', res); var url = window.URL.createObjectURL(res.data); var a = document.createElement('a'); document.body.appendChild(a); a.setAttribute('style', 'display: none'); a.href = url; a.download = res.filename; a.click(); window.open(url); a.remove(); } ) }
Descargar Archivos ZIPREST
@RequestMapping(value = "/obtenerDocumentoZip", method = RequestMethod.GET, produces = "application/zip")
public void doDownload(HttpServletRequest request, HttpServletResponse response, @RequestParam String sidCliente,
@RequestParam String idCompania, @RequestParam Integer idDocumento) throws IOException {
UsuarioActual usuario = new UsuarioActual();
usuario.setSidCliente(sidCliente);
DtoDocumento documento = consulta.obtenerDocumentoZip(usuario, idCompania, idDocumento);
if (documento.getFlgEncontrado()) {
File downloadFile = new File(documento.getRutaCompleta());
FileInputStream inputStream = new FileInputStream(downloadFile);
String mimeType = "application/octet-stream";
System.out.println("MIME type: " + mimeType);
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
}
ANGULAR
obtenerDocumentoZip(idDocumento: number, idCompania: string) { const type = 'application/zip'; const filename = 'file.zip'; const params = new URLSearchParams(); params.set("idDocumento", JSON.stringify(idDocumento * 1)); params.set("idCompania", idCompania); params.set("sidCliente", this.sid); const options = new RequestOptions({ responseType: ResponseContentType.Blob, search: params, headers: new Headers({ 'Accept': type }) });this.http.get(`${this.url}obtenerDocumentoZip`, options) .catch(errorResponse => Observable.throw(errorResponse.json())) .map((response) => { if (response instanceof Response) { return response.blob(); } return response; }) .subscribe(data => saveAs(data, filename), error => console.log(error)); // implement your error handling here}1.- FORMA DE SUBIR UN ARCHIVO EXCELUSA UN JAR.<dependency><groupId>com.gizbel.excel</groupId><artifactId>excel-extractor</artifactId><version>1.0.2</version></dependency>USA UN BEAN CONFIGURADO@ExcelBeanpublic class Example {@ExcelColumnIndex(columnIndex = "1", dataType = "string")private String codigo;@ExcelColumnIndex(columnIndex = "2", dataType = "string")private String nombre;@ExcelColumnIndex(columnIndex = "3", dataType = "double")private Integer precio;CREA ARCHIVO EN MEMORIApublic File multipartToFile(MultipartFile multipart) throws IllegalStateException, IOException {File tmpFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator")+ multipart.getOriginalFilename());multipart.transferTo(tmpFile);return tmpFile;}OBTIENE LA LISTA DEL EXCEL ENVIADOParser parser = new Parser(Example.class, ExcelFactoryType.COLUMN_INDEX_BASED_EXTRACTION);parser.setSkipHeader(true);File resultado=multipartToFile(file);List<Object> result = parser.parse(resultado);for (Object obj : result) {Example ex = (Example) obj;}2.- FORMA DE TRABAJAR EL EXCELUSA JAR (APACHE POI)Boolean grabar = false;Workbook workbook = new XSSFWorkbook(file.getInputStream());Sheet firstSheet = workbook.getSheetAt(0);Iterator<Row> iterator = firstSheet.iterator();List<DtoPlantillaServicio> listaServicio = new ArrayList<DtoPlantillaServicio>();while (iterator.hasNext()) {Row nextRow = iterator.next();Iterator<Cell> cellIterator = nextRow.cellIterator();DtoPlantillaServicio obj = new DtoPlantillaServicio();while (cellIterator.hasNext()) {Cell cell = cellIterator.next();if (cell.getRowIndex() > 1) {grabar = true;switch (cell.getColumnIndex()) {case 1:obj.setCodigo(obtenerCelda(cell));break;case 2:obj.setNombre(obtenerCelda(cell));break;case 3:obj.setPrecioCosto(new BigDecimal(obtenerCelda(cell)));break;case 4:obj.setPrecioVenta(new BigDecimal(obtenerCelda(cell)));break;}}}if (grabar) {listaServicio.add(obj);}}private String obtenerCelda(Cell celda) {String celdaRetorno = null;switch (celda.getCellType()) {case Cell.CELL_TYPE_STRING:celdaRetorno = celda.getStringCellValue();break;case Cell.CELL_TYPE_NUMERIC:celdaRetorno = String.valueOf(celda.getNumericCellValue());break;}return celdaRetorno;}ANGULARobtenerServicio(file: File): Observable<HttpEvent<{}>> { const formdata: FormData = new FormData(); formdata.append('file', file); const req = new HttpRequest('POST', 'tu ruta', formdata, { reportProgress: true, responseType: 'text' }); return this.httpCliente.request(req); }API REST@RequestMapping(method = RequestMethod.POST, produces = "application/json; charset=UTF-8", path = "/obtenerServicio") public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) { String message = ""; try { files.add(file.getOriginalFilename()); UsuarioActual usuarioActual= new UsuarioActual(); this.servicio.servicioCargar(usuarioActual, file); message = "You successfully uploaded " + file.getOriginalFilename() + "!"; return ResponseEntity.status(HttpStatus.OK).body(message); } catch (Exception e) { message = "FAIL to upload " + file.getOriginalFilename() + "!"; return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message); } }
No hay comentarios:
Publicar un comentario