Image uploading integration test of RESTful webservice with spring mvc - java

How to write a integration test when I'm uploading a image to the server. I've already written a test following this question and it's answer but mine is not working properly. I used JSON to send the image and expected status OK. But I'm getting:
org.springframework.web.utill.NestedServletException:Request
Processing Failed;nested exception is java.lang.illigulArgument
or http status 400 or 415. I guess the meaning is same. Below I've given my test portion and controller class portion.
Test portion:
#Test
public void updateAccountImage() throws Exception{
Account updateAccount = new Account();
updateAccount.setPassword("test");
updateAccount.setNamefirst("test");
updateAccount.setNamelast("test");
updateAccount.setEmail("test");
updateAccount.setCity("test");
updateAccount.setCountry("test");
updateAccount.setAbout("test");
BufferedImage img;
img = ImageIO.read(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg"));
WritableRaster raster = img .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] testImage = data.getData();
updateAccount.setImage(testImage);
when(service.updateAccountImage(any(Account.class))).thenReturn(
updateAccount);
MockMultipartFile image = new MockMultipartFile("image", "", "application/json", "{\"image\": \"C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg\"}".getBytes());
mockMvc.perform(
MockMvcRequestBuilders.fileUpload("/accounts/test/updateImage")
.file(image))
.andDo(print())
.andExpect(status().isOk());
}
Controller portion:
#RequestMapping(value = "/accounts/{username}/updateImage", method = RequestMethod.POST)
public ResponseEntity<AccountResource> updateAccountImage(#PathVariable("username") String username,
#RequestParam(value="image", required = false) MultipartFile image) {
AccountResource resource =new AccountResource();
if (!image.isEmpty()) {
try {
resource.setImage(image.getBytes());
resource.setUsername(username);
} catch (IOException e) {
e.printStackTrace();
}
}
Account account = accountService.updateAccountImage(resource.toAccount());
if (account != null) {
AccountResource res = new AccountResourceAsm().toResource(account);
return new ResponseEntity<AccountResource>(res, HttpStatus.OK);
} else {
return new ResponseEntity<AccountResource>(HttpStatus.EXPECTATION_FAILED);
}
}
If I write my controller this way It shows IllegalArgument in Junit trace but no problem in console and no mock print as well. So, I replace Controller with this:
#RequestMapping(value = "/accounts/{username}/updateImage", method = RequestMethod.POST)
public ResponseEntity<AccountResource> updateAccountImage(#PathVariable("username") String username,
#RequestBody AccountResource resource) {
resource.setUsername(username);
Account account = accountService.updateAccountImage(resource.toAccount());
if (account != null) {
AccountResource res = new AccountResourceAsm().toResource(account);
return new ResponseEntity<AccountResource>(res, HttpStatus.OK);
} else {
return new ResponseEntity<AccountResource>(HttpStatus.EXPECTATION_FAILED);
}
}
Than I have this output in console:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /accounts/test/updateImage
Parameters = {}
Headers = {Content-Type=[multipart/form-data;boundary=265001916915724]}
Handler:
Type = web.rest.mvc.AccountController
Method = public org.springframework.http.ResponseEntity<web.rest.resources.AccountResource> web.rest.mvc.AccountController.updateAccountImage(java.lang.String,web.rest.resources.AccountResource)
Async:
Was async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.HttpMediaTypeNotSupportedException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 415
Error message = null
Headers = {Accept=[application/octet-stream, text/plain;charset=ISO-8859-1, application/xml, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, application/json;charset=UTF-8, application/*+json;charset=UTF-8, */*]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Now, I need to know how to solve this problem or should I take another approach and what is that.

The problem was because controller class is meant to receive multipart/form-data,but sent JSON data. There is another problem in this code. The controller returns the resource that having image inside. That causing processing failed. Right code is given below:
#test portion
Account updateAccount = new Account();
updateAccount.setPassword("test");
updateAccount.setNamefirst("test");
updateAccount.setNamelast("test");
updateAccount.setEmail("test");
updateAccount.setCity("test");
updateAccount.setCountry("test");
updateAccount.setAbout("test");
BufferedImage img;
img = ImageIO.read(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg"));
WritableRaster raster = img .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
byte[] testImage = data.getData();
updateAccount.setImage(testImage);
FileInputStream fis = new FileInputStream("C:\\Users\\Public\\Pictures\\Sample Pictures\\Penguins.jpg");
MockMultipartFile image = new MockMultipartFile("image", fis);
HashMap<String, String> contentTypeParams = new HashMap<String, String>();
contentTypeParams.put("boundary", "265001916915724");
MediaType mediaType = new MediaType("multipart", "form-data", contentTypeParams);
when(service.updateAccountImage(any(Account.class))).thenReturn(
updateAccount);
mockMvc.perform(
MockMvcRequestBuilders.fileUpload("/accounts/test/updateImage")
.file(image)
.contentType(mediaType))
.andDo(print())
.andExpect(status().isOk());
Controller Portion:
#RequestMapping(value = "/{username}/updateImage", method = RequestMethod.POST)
public #ResponseBody
ResponseEntity<AccountResource> updateAccountImage(#PathVariable("username") String username,
#RequestParam("image") final MultipartFile file)throws IOException {
AccountResource resource =new AccountResource();
resource.setImage(file.getBytes());
resource.setUsername(username);
Account account = accountService.updateAccountImage(resource.toAccount());
if (account != null) {
AccountResource res = new AccountResourceAsm().toResource(account);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity<AccountResource>(res,headers, HttpStatus.OK);
} else {
return new ResponseEntity<AccountResource>(HttpStatus.NO_CONTENT);
}
}

I can test this using apache.commons.httpClient library like shown below
#Test
public void testUpload() {
int statusCode = 0;
String methodResult = null;
String endpoint = SERVICE_HOST + "/upload/photo";
PostMethod post = new PostMethod(endpoint);
File file = new File("/home/me/Desktop/someFolder/image.jpg");
FileRequestEntity entity = new FileRequestEntity(file, "multipart/form-data");
post.setRequestEntity(entity);
try {
httpClient.executeMethod(post);
methodResult = post.getResponseBodyAsString();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
statusCode = post.getStatusCode();
post.releaseConnection();
//...
}

Related

Java Upload file Rest Template

I need to upload a file through the spring MVC rest template for the below params shown in the image.
I have tried different approaches but it's not working giving exception 401 Unauthorized.
I need code that uploads files through spring MVC RestTemplate.
I have shared my code below which is not working.I have tried different ways to attach file but they are not working please check my code.
My Code Sample:
#RequestMapping(value = "/uploadPEFile", method = { RequestMethod.POST},
produces = "application/json")
#ResponseBody
public String uploadPEFile(#RequestParam(value = "file", required = false) MultipartFile file,
HttpServletRequest request, HttpServletResponse httpResponse) {
JsonResponse objResponse = null;
String enterpriseId = "";
String enterpriseName = "";
String type = "";
String productId = "";
String userIds = "";
String title = "";
String description = "";
String date = "";
String externalUrl = "";
String presenterName = "";
try {
enterpriseId = request.getParameter("enterpriseId");
enterpriseName = request.getParameter("enterpriseName");
type = request.getParameter("type");
productId = request.getParameter("productId");
userIds = request.getParameter("userIds");
title = request.getParameter("title");
description = request.getParameter("description");
date = request.getParameter("date");
if(date != null && !date.isEmpty())
{
String [] dateArray = date.split(" ");
date = dateArray[2]+" "+getMonth(dateArray[1])+", "+dateArray[3];
}
externalUrl = request.getParameter("externalURL");
presenterName = request.getParameter("presenterName");
JsonObject jsonBody = new JsonObject();
jsonBody.addProperty("title", title);
jsonBody.addProperty("description", description);
jsonBody.addProperty("date", date);
jsonBody.addProperty("external_url", externalUrl);
jsonBody.addProperty("presenter_name", presenterName);
String cmsDeviceId = PortalUtil.getPropertyValue("cms.device.id");
if (file != null) {
final String filename = file.getOriginalFilename();
ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
#Override
public String getFilename() {
return filename;
}
};
String filePath = "/persivia edge/"+type+"/"+filename;
File userFile = new File(System.getProperty(PortalConstants.cdnPath) + filePath);
if(!userFile.exists()) {
userFile.mkdirs();
}
file.transferTo(userFile);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("device_id",cmsDeviceId);
// body.add("attachment",fileAsResource);
// body.add("attachment",new MultipartInputStreamFileResource(file.getInputStream(), file.getOriginalFilename()));
body.add("attachment",new FileSystemResource(filePath));
body.add("source", "web");
body.add("filename", filename);
body.add("enterprise_id", enterpriseId);
body.add("enterpriseName", enterpriseName);
body.add("type", type);
body.add("product_id",productId);
body.add("userIds",userIds);
body.add("body", jsonBody.toString());
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
RestTemplate restTemplate = new RestTemplate();
String requestUrl = PortalUtil.getPropertyValue("cms.api.url")+"wp-json/wp/v2/upload_content";
String response = restTemplate.postForObject(requestUrl, requestEntity, String.class);
httpResponse.setStatus(HttpServletResponse.SC_OK);
JsonObject data = new JsonObject();
objResponse = JsonResponse.build(ResponseStatus.status200, ResponseStatus.message200,
"Logo info updated successfully", data);
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e.getCause());
objResponse = JsonResponse.build(ResponseStatus.status500, ResponseStatus.message500,
e.getMessage(), null);
httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
return new Gson().toJson(objResponse);
}

Rest-Api Call Other Rest-Api In Spring boot Not Working for (Multipart-File)

I need your help. I have 2 Api in Same Class both use for Upload the file. I'm trying to upload the file from 1 api to other api by using of RestTemplate but it's show error like.
Error :- MessageType definition error: [simple type, class java.io.FileDescriptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.FileDescriptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile["inputStream"]->java.io.FileInputStream["fd"])
File Store Api Not Calling through RestTemplate due to above error.
API-1:- File Store Api
#RequestMapping(value = PathConst.UPLOAD_MULTIPART_FILE, method = RequestMethod.POST)
public ResponseEntity<?> uploadMultipleFiles(#RequestPart("files") #NotNull List<MultipartFile> files) {
try {
this.apiResponse = new APIResponse();
// Note :- 'here this upload file dto help to collect the non-support file info'
List<UploadFileDto> wrongTypeFile = files.stream().
filter(file -> {
return !isSupportedContentType(file.getContentType());
}).map(file -> {
UploadFileDto wrongTypeFileDto = new UploadFileDto();
wrongTypeFileDto.setSize(String.valueOf(file.getSize()));
wrongTypeFileDto.setFileName(file.getOriginalFilename());
wrongTypeFileDto.setContentType(file.getContentType());
return wrongTypeFileDto;
}).collect(Collectors.toList());
if(!wrongTypeFile.isEmpty()) { throw new FileStorageException(wrongTypeFile.toString()); }
this.apiResponse.setReturnCode(HttpStatus.OK.getReasonPhrase());
this.apiResponse.setMessage("File Store Success full");
this.apiResponse.setEntity(
files.stream().map(file -> {
String fileName = this.fileStoreManager.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path(PathConst.FILE + PathConst.DOWNLOAD_FILE).path(fileName).toUriString();
UploadFileDto uploadFile = new UploadFileDto();
uploadFile.setFileName(fileName);
uploadFile.setUrl(fileDownloadUri);
uploadFile.setSize(String.valueOf(file.getSize()));
return uploadFile;
}).collect(Collectors.toList()));
}catch (Exception e) {
System.out.println("Message" + e.getMessage());
this.errorResponse = new ExceptionResponse();
this.errorResponse.setErrorCode(HttpStatus.BAD_REQUEST.getReasonPhrase());
this.errorResponse.setErrorMessage("Sorry! Filename contains invalid Type's,");
this.errorResponse.setErrors(Collections.singletonList(e.getMessage()));
return new ResponseEntity<ExceptionResponse>(this.errorResponse, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<APIResponse>(this.apiResponse, HttpStatus.OK);
}
API-2:- Product Store Api With List Of Image File
#RequestMapping(value = "/save/product", method = RequestMethod.POST)
public ResponseEntity<?> saveProduct(#Valid #RequestPart("request") ProductDto productDto, #RequestPart("files") #NotNull List<MultipartFile> files) {
try {
this.apiResponse = new APIResponse();
this.restTemplate = new RestTemplate();
if(!files.isEmpty()) { new NullPointerException("List of File Empty"); }
// call-api of File controller
try {
// file's
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
files.stream().forEach(file -> { body.add("files", file); });
// header-type
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// request real form
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(body, headers);
// request-url
this.RESOURCE_URL = ServletUriComponentsBuilder.fromCurrentContextPath().path(PathConst.FILE + PathConst.UPLOAD_MULTIPART_FILE).toUriString();
// response-result
System.out.println(this.restTemplate.exchange(this.RESOURCE_URL, HttpMethod.POST, request, Object.class).getStatusCode());
// if(!response.getStatusCode().equals(200)) {
// // error will send
// }
}catch (NullPointerException e) {
throw new NullPointerException("Product Image's Not Save Scuessfully. " + e);
}
}catch (Exception e) {
System.out.println("Message" + e.getMessage());
this.errorResponse = new ExceptionResponse();
this.errorResponse.setErrorCode(HttpStatus.NO_CONTENT.getReasonPhrase());
this.errorResponse.setErrorMessage(e.getMessage());
return new ResponseEntity<ExceptionResponse>(this.errorResponse, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<APIResponse>(this.apiResponse, HttpStatus.OK);
}
Main Code :-
try {
// file's
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
files.stream().forEach(file -> { body.add("files", file); });
// header-type
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// request real form
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(body, headers);
// request-url
this.RESOURCE_URL = ServletUriComponentsBuilder.fromCurrentContextPath().path(PathConst.FILE + PathConst.UPLOAD_MULTIPART_FILE).toUriString();
// response-result
System.out.println(this.restTemplate.exchange(this.RESOURCE_URL, HttpMethod.POST, request, Object.class).getStatusCode());
//if(!response.getStatusCode().equals(200)) {
// // error will send
//}
}catch (NullPointerException e) {
throw new NullPointerException("Product Image's Not Save Scuessfully. " + e);
}
I was facing the same issue , but using the below code i fixed it.
#RequestMapping("/upload")
public void postData(#RequestParam("file") MultipartFile file) throws IOException {
String url = "https://localhost:8080/upload";
MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
bodyMap.add("file", new FileSystemResource(convert(file)));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.exchange(url,
HttpMethod.POST, requestEntity, String.class);
}
public static File convert(MultipartFile file)
{
File convFile = new File(file.getOriginalFilename());
try {
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convFile;
}
I solve this issue by adding the these line's
files.stream().forEach(file -> {
System.out.println(file.getOriginalFilename());
Resource resouceFile = new FileSystemResource(file.getBytes(), file.getOriginalFilename());
body.add("files", resouceFile);
});
public static class FileSystemResource extends ByteArrayResource {
private String fileName;
public FileSystemResource(byte[] byteArray , String filename) {
super(byteArray);
this.fileName = filename;
}
public String getFilename() { return fileName; }
public void setFilename(String fileName) { this.fileName= fileName; }
}
Make use of multipartFile.getResource() - neat and simple solution
public void exFunction(MultipartFile multipartFile) throws IOException {
Resource multipartFile = multipartFile.getResource();
LinkedMultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
parts.add("file", multipartFile);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> httpEntity = new
HttpEntity<>(parts, httpHeaders);
restTemplate.postForEntity("my/url", httpEntity, SommeClass.class);
}

Unit testing an endpoint with #RequestBody

So I am getting a 400 for my HTTP response code when it should be 200. I am passing in a byte[] object to the endpoint but it doesn't seem to be adding the content-type correctly? Any suggestions?
#RequestMapping(value = "/test", method = RequestMethod.POST, consumes = "application/octet-stream")
public ResponseEntity<String> receiveCompressedBinary(#RequestHeader String site, #RequestHeader String customer,
#RequestHeader String table, #RequestBody byte[] binary, #RequestHeader String loadStatus) {
if(binary.length < maxFileSize) {
return new ResponseEntity<String>(HttpStatus.OK);
}
else{
return new ResponseEntity<String>(HttpStatus.PAYLOAD_TOO_LARGE);
}
}
My test:
#Test
public void testUploadCompressedBinaryInitialRunning() throws Exception{
File file = new File("src/test/resources/testFile.txt");
String site = "site";
String customer = "customer";
String table = "table";
String loadStatus = "INITIALRUNNING";
this.mockMvc.perform(post("/test").header("site",site).param("customer",customer).
param("table", table).content(compress(file)).param("loadStatus",loadStatus)
.with(user("user"))).andExpect(status().isOk());
this.mockMvc.perform(post("/uploadCompressedBinary")).andDo(print()).andExpect(status().isOk());
}
Compress method:
public static byte[] compress(File file) throws IOException {
if (file.length() == 0) {
return null;
}
FileInputStream fileInputStream = null;
byte[] fileInBytes = new byte[(int)file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(fileInBytes);
fileInputStream.close();
} catch (IOException e) {
System.out.println("Exception whilst compressing the file: " + e.getMessage());
}
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(fileInBytes);
gzip.close();
return obj.toByteArray();
}
UPDATE: Got past it, rather than .param, I should be using .header
It does not look like you are setting the content type when you are posting.
Try
this.mockMvc.perform(post("/test").header("site",site).param("customer",customer).
param("table", table).content(compress(file)).contentType("application/octet-stream").param("loadStatus",loadStatus)
.with(user("user"))).andExpect(status().isOk());

Spring boot Birt Report with Angular 2 client Generates Corrupt PDF File

I am trying to configure birt report in a spring boot applications, the client is an angular 2 application, here is where I run the report:
#PostConstruct
public void startUp() {
if(inputDir == null)
throw new RuntimeException("Cannot start application since birt report input directory was not specified.");
try {
EngineConfig engineConfig = new EngineConfig();
engineConfig.getAppContext().put("spring", this.context);
RegistryProviderFactory.releaseDefault();
Platform.startup(engineConfig);
IReportEngineFactory reportEngineFactory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
birtReportEngine = reportEngineFactory.createReportEngine(engineConfig);
} catch (BirtException e) {
}
reportOutputDirectory = env.getProperty("birt_temp_file_output_dir");
}
#Override
public ByteArrayOutputStream runReport(Report birtReport) {
ByteArrayOutputStream byteArrayOutputStream;
File rptDesignFile;
try {
rptDesignFile = getReportFromFilesystem(birtReport.getName());
} catch (Exception e) {
throw new RuntimeException("Could not find report");
}
Map<String, String> parsedParameters = parseParametersAsMap(birtReport.getParameters());
byteArrayOutputStream = new ByteArrayOutputStream();
try {
IReportRunnable reportDesign = birtReportEngine.openReportDesign(rptDesignFile.getPath());
IRunTask runTask = birtReportEngine.createRunTask(reportDesign);
if (parsedParameters.size() > 0) {
for (Map.Entry<String, String> entry : parsedParameters.entrySet()) {
runTask.setParameterValue(entry.getKey(), entry.getValue());
}
}
runTask.validateParameters();
String rptdocument = reportOutputDirectory + File.separator
+ "generated" + File.separator
+ birtReport.getName() + ".rptdocument";
runTask.run(rptdocument);
IReportDocument reportDocument = birtReportEngine.openReportDocument(rptdocument);
IRenderTask renderTask = birtReportEngine.createRenderTask(reportDocument);
PDFRenderOption pdfRenderOption = new PDFRenderOption();
pdfRenderOption.setOption(IPDFRenderOption.REPAGINATE_FOR_PDF, new Boolean(true));
pdfRenderOption.setOption(IPDFRenderOption.PAGE_OVERFLOW, IPDFRenderOption.OUTPUT_TO_MULTIPLE_PAGES );
pdfRenderOption.setOption(IPDFRenderOption.PDF_TEXT_WRAPPING , true);
pdfRenderOption.setOption(IPDFRenderOption.PDF_HYPHENATION , true);
pdfRenderOption.setOutputFormat("pdf");
pdfRenderOption.setOutputStream(byteArrayOutputStream);
renderTask.setRenderOption(pdfRenderOption);
renderTask.render();
renderTask.close();
} catch (EngineException e) {
throw new RuntimeException();
}
return byteArrayOutputStream;
}
and this is the api service that returns the byte array:
#RequestMapping(value = "/birt", method = RequestMethod.POST)
public ResponseEntity<byte[]> getBIRTReport(#RequestBody ReportRequest reportRequest) {
byte[] reportBytes;
ResponseEntity<byte[]> responseEntity;
try {
reportBytes =
new BIRTReport(
reportRequest.getReportName(),
reportRequest.getReportParameters(),
reportRunner)
.runReport().getReportContent().toByteArray();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.parseMediaType("application/pdf"));
String fileName = reportRequest.getReportName() + ".pdf";
httpHeaders.setContentDispositionFormData(fileName, fileName);
httpHeaders.setCacheControl("must-revalidate, post-check=0, pre-check=0");
responseEntity = new ResponseEntity<byte[]>(reportBytes, httpHeaders, HttpStatus.OK);
} catch (Exception e) {
responseEntity = new ResponseEntity<byte[]>(HttpStatus.NOT_IMPLEMENTED);
return responseEntity;
}
return responseEntity;
}
and that is the angular 2 code:
public getReport():Observable<any>{
let params = {
"reportName":"my report name",
"reportParameters":"my params"
};
let headers = new Headers();
headers.append('Content-Type','application/json');
let options = new RequestOptions({headers: headers});
return this.http.post("http://localhost:8080/reports/birt",JSON.stringify(params), options);
}
call the service:
getReport(){
this.reportService.getReport().subscribe(
data => {
var blob = new Blob([data._body], { type: 'application/pdf'})
saveAs(blob, "myPdf.pdf");
var fileUrl = URL.createObjectURL(blob);
window.open(fileUrl);
}
)
}
This method returns a corrupt file, can anyone figure out the problem?
The problem is that you are missing responseType in options
let options = new RequestOptions({headers: headers, **responseType: ResponseContentType.Blob**});
After that you can just do
window['saveAs'](response.blob(), 'filename.zip');

Display image stored as blob using GWT Jersy Rest

I am not able to display an image stored as blob returned by a rest service :
This is the rest service code that returns the blob stored image coded into base64 :
#GET
#Path("/get")
#Produces("image/jpeg")
public Response getFile() {
String base64 = getStringImage();
ResponseBuilder response = Response.ok((Object) base64);
return response.build();
}
String getStringImage() {
try {
AnounceService anounceService = (AnounceService)getApplicationContext().getBean("AnounceService");
Blob imageBlob = anounceService.getStgImage();
int blobLength = (int)imageBlob.length();
byte[] buff = imageBlob.getBytes(1, blobLength);
String base64=Base64Utils.toBase64(buff);
return base64;
} catch (Exception exc) {
}
return null;
}
This is the gwt client code that fails to display the image returned by the above rest code :
String url = "root/api/image/get";
final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);Image img;
builder.setCallback(new RequestCallback() {
public void onResponseReceived(final Request request, final Response response) {
if (response.getStatusCode() == Response.SC_OK) {
final HTML imageHolder = new HTML();
String base64 = response.getText();
String imgTag = "<img src='data:image/gif;base64,"+base64+"' />'";
imageHolder.setHTML(imgTag);
RootPanel.get().add(imageHolder);
}
}
There is no error triggered, but I don't see any image displayed in the browser.

Categories