spring 3 file upload using CommonsMultipartResolver not working properly - spring-mvc

I am using CommonsMultipartResolver to upload a word/pdf file into postgres database, while uploading the file I have printed the byte[] array using file.getBytes(), it showing like
bytes==========================[B#6b02547c
the file is being upload but when I download the file I am getting the following error from ms-word: "The file abc.docx cannot be opened because there are problems with contents". please help me to solve this problem.
#SuppressWarnings({ "unused", "static-access" })
#RequestMapping( value="/RegisterCandidate" , method = RequestMethod.POST)
private String RegisterCandidate(HttpServletRequest request,
HttpServletResponse response,
#RequestParam CommonsMultipartFile[] fileUpload ) throws Exception{
System.out.println("In method");
String email = request.getParameter("email");
System.out.println("email==============="+email);
String Password = request.getParameter("password");
String usr_name = request.getParameter("name");
String mobile_no = request.getParameter("mobile_no");
Date dateentry = new Date();
java.sql.Timestamp entry_date = new Timestamp(dateentry.getTime());
Users_Pojo usr = new Users_Pojo();
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload){
usr.setFilename(aFile.getOriginalFilename());
usr.setFile_data(aFile.getBytes());
System.out.println("aFile.getBytes()======"+aFile.getBytes());
System.out.println("aFile.getInputStream()======"+aFile.getInputStream());
System.out.println("aFile.getStorageDescription()======"+aFile.getStorageDescription());
System.out.println("aFile.getSize();======"+aFile.getSize());
System.out.println("aFile.getContentType();==="+aFile.getContentType());/* */
}
}
usr.setUc_password("ex123");
usr.setUc_name(email);
usr.setUc_contact_person(email);
usr.setUc_phone_no(BigInteger.valueOf(Long.parseLong(mobile_no)));
usr.setUc_email_id(email);
usr.setUc_type_id(1);
usr.setUc_active(1);
usr.setValid_from(null);
usr.setValid_to(null);
usr.setDesignation("jobseekar");
usr.setIp_address("164.100.200.179");
usr.setUser_location(1);
usr.setEntry_date(entry_date);
scm_service.save(usr, email);
/*System.out.println("email==="+email);
System.out.println("Password==="+Password);
System.out.println("usr filename==="+usr.getFilename());*/
return "success";
//return "redirect:Login.html";
}
Configuration:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2000000" />
</bean>
downloading using :
#RequestMapping(value = "/download",method = RequestMethod.GET)
public void getAttachmenFromDatabase( HttpServletRequest request,HttpServletResponse response){
response.setContentType("application/vnd.ms-word");
String resume_id = request.getParameter("resume_id");
long attachid = Long.parseLong(resume_id);
try {
Users_Pojo file_attachment = (Users_Pojo) scm_service.getFiles(attachid);
System.out.println("file_attachment.getFilename()======="+file_attachment.getFile_data());
response.setHeader("Content-Disposition", "inline; filename=\""+ file_attachment.getFilename() +"\"");
response.setContentLength(file_attachment.getFile_data().length);
FileCopyUtils.copy(file_attachment.getFile_data(), response.getOutputStream());
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

Spring Boot MVC -> Excel data corrupted on download

I am using ModelAndView pattern to return excel representation of data that is generated in the Controller using Apache POI library.
However the excel gets corrupted(special characters are replaced with ?) when it gets downloaded. If I write the excel to file before pushing it out on the HTTP response, then a valid excel is output.
Here is the controller code that pushes control to ModelAndView
Map<String, Object> model = new HashMap<String, Object>();
model.put(ExcelBusinessReportView.KEY_REPORT_DISPLAY_DATA, reportData);
model.put(ExcelBusinessReportView.KEY_REPORT_DATE, reportRequestDTO.getReportDateUTCAtMidnight());
return new ModelAndView("excelBusinessReportView", model);
And here is the view class
#Service(value = "excelBusinessReportView")
public class ExcelBusinessReportView extends AbstractXlsView {
public static final String KEY_REPORT_DISPLAY_DATA = "reportData";
public static final String KEY_REPORT_DATE = "reportDate";
private static final String MIME_TYPE_EXCEL = "application/ms-excel";
private static final String HEADER_VALUE_CONTENT_DISPOSITION = "attachment; filename=qup_report.xls";
private static final String[] SUMMARY_HEADERS = ........
private static final String[] DETAIL_HEADERS = ........
#Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
BusinessSlotReportResource reportDisplayData = (BusinessSlotReportResource) model.get(KEY_REPORT_DISPLAY_DATA);
DateTime reportDate = (DateTime) model.get(KEY_REPORT_DATE);
// Build excel document
Sheet sheet = workbook.createSheet(reportDate.toString(CommonConstants.IST_DATE_FORMATTER_PATTERN));
sheet.setDefaultColumnWidth((short) 12);
Integer currentRow = 0;
// Build summary data
currentRow = this.buildSummaryData(workbook, sheet, reportDisplayData, currentRow);
// Create margin rows
sheet.createRow(currentRow++);
sheet.createRow(currentRow++);
// Build detail data
this.buildDetailsData(workbook, sheet, reportDisplayData, currentRow);
response.setContentType(MIME_TYPE_EXCEL);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, HEADER_VALUE_CONTENT_DISPOSITION);
}
Content of excel when written to file in the view
–œ‡°±·;˛ˇ ˛ˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇRoot Entryˇˇˇˇˇˇˇˇ#Workbookˇˇˇˇˇˇˇˇˇˇˇˇ˛ˇˇˇ˝ˇˇˇ˛ˇˇˇ ˛ˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇ
 !"#$%&'()*+,-./0˛ˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇˇ ”ÃA·∞¡‚\panilallewar
Same part of the excel when downloaded
��ࡱ�;�� ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Root Entry��������#Workbook������������������������ ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
 !"#$%&'()*+,-./0�������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� ��A����\panilallewar
Usually instead of putting the file in the model I write it directly in the response.
The following code is for xlsx format, but the concept is the same for previous versions of excel.
This endpoint is accepting a JSON which will be mapped to MyPojo.
#RequestMapping(value = "exportToExcel", method = RequestMethod.POST)
public #ResponseBody HttpEntity<byte[]> generateExcel(#Valid #RequestBody final MyPojo data) throws IOException {
final File file = File.createTempFile("MyExcelReport", "xlsx");
file.deleteOnExit();
final Path path = file.toPath();
try (final FileOutputStream fileOut = new FileOutputStream(file)) {
try (final XSSFWorkbook workbook = new XSSFWorkbook()) {
final XSSFSheet sheet = workbook.createSheet(SHEET_NAME);
//fill your excel sheets
workbook.write(fileOut);
final byte[] byteArray = Files.readAllBytes(path);
final HttpHeaders header = new HttpHeaders();
header.setContentType(new MediaType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
header.set("Content-Disposition", "inline; filename=MyExcelReport.xlsx");
header.setContentLength(byteArray.length);
return new HttpEntity<>(byteArray, header);
} catch (final Exception e) {
LOG.error("Error during creation of excel report", e);
throw e;
} finally {
if (path != null) {
try {
Files.delete(path);
} catch (final IOException e) {
LOG.error("Unable to delete file:" + path.toString(), e);
}
}
}
}
}
Also if you are using a frontend framework like angular you have to properly setup the response type (https://stackoverflow.com/a/52703842/3657208)

How To Configure log4j2.xml for HTTP-Appender

I need assistance in configuring HTTP-Appender in log4j2.xml. I have made multiple attempt to configure it using both JSONLayout and PatternLayout, neither worked. Here is my code snippet.
<Http name="HTTP_APPENDER" url="http://localhost:8080/test/logRest" method="POST">
<Property name="x-java-runtime" value="$${java:runtime}" />
<PatternLayout pattern="%-5p | %d{yyyy-MM-dd HH:mm:ss} | [%t] %C{2} (%F:%L) - %m%n"/>
</Http>
=====================================================================
#RequestMapping(value = "/logRest", method = RequestMethod.POST)
public void logRest(HttpServletRequest request,HttpServletResponse response, Model model){
Enumeration<String> y = request.getHeaderNames();
while (y.hasMoreElements()) {
String param = y.nextElement();
String value = request.getHeader(param);
System.out.println(param + "=" + value);
}
System.out.println("====================================");
Enumeration<String> x = request.getParameterNames();
while (x.hasMoreElements()) {
String param = x.nextElement();
String value = request.getParameter(param);
System.out.println(param + "=" + value);
}
}
==================================================================
I need to get the logged data, but it's not showing in the header,parameter or even the request attributes. I will appreciate any form of assistance to get the logged data sent to the URL endpoint.
Cheers.
See the solution below
/**
* Reads the request body from the request and returns it as a String.
*
* #param request HttpServletRequest that contains the request body
* #return request body as a String or null
*/
private String readRequestBody(HttpServletRequest request) {
try {
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (Exception e) {
//logger.error("Failed to read the request body from the request.");
}
return null;
}

Spring4 Aop on Spring mvc controller error

code:
#Aspect
#Order(Integer.MAX_VALUE)
public class KeySortedAspect {
#Pointcut(value = "#annotation(com.le.bigdata.convertor.KeySortedRule)")
public void pointCut(){}
#Around(value = "pointCut()")
public Object keySorted(ProceedingJoinPoint joinPoint) throws Throwable {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Object result = joinPoint.proceed();
if(methodSignature.getMethod().isAnnotationPresent(KeySortedRule.class)){
KeySortedRule keySortedRule = methodSignature.getMethod().getAnnotation(KeySortedRule.class);
String path = keySortedRule.path();
//String rule = keySortedRule.rule();
try {
Map<String, String[]> keyMap = getRule(path);
Class<?> type = methodSignature.getMethod().getReturnType();
Object a = sortedUseKeyList(result, keyMap, type);
return a;
} catch (IOException e) {
logger.error("Key sorted Error");
logger.error("reason ", e);
}
}
return result;
}
}
spring mvc configuration mvc-dispatcher-servlet.xml:
<context:annotation-config />
<!-- controller层 内部ctrl与lebi对接的ctrl -->
<context:component-scan base-package="com.le.bigdata.controller, com.le.bigdata.api.controller"/>
<bean id="keySortedAspect" class="com.le.bigdata.convertor.KeySortedAspect"/>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<mvc:default-servlet-handler/>
controller code:
#RestController
#RequestMapping("cp")
public class ContentPortraitController {
#Autowired
private IContentPortraitService service;
#RequestMapping(value = "usertop", method = RequestMethod.GET)
#ApiOperation(value = "获取默认的cv排名前10名的专辑")
private CommonResponseDTO getUserTop(#RequestParam(defaultValue = "10") int size){
List<Map<String, Object>> list = service.getDefaultPid(size);
return new CommonResponseDTO(true, list);
}
#RequestMapping(value = "/album", method = RequestMethod.GET)
#ApiOperation(value = "获取专辑画像", httpMethod = "GET")
#KeySortedRule(path="content_portrait")
public JSONObject getAlbum(#RequestParam(value="dt",required = false) String dt,
#RequestParam(value="start_dt",required = false) String start,
#RequestParam(value="end_dt",required = false) String end,
#RequestParam(value="product",required = false) List<String> product,
#RequestParam(value="pid") String pid){
JSONObject result = new JSONObject();
JSONObject data = null;
try {
if(dt != null && !dt.isEmpty()){
//
data = service.getAlbumPortrait(pid, dt, product);
} else if(start != null && end != null && !start.isEmpty() && !end.isEmpty()){
//
data = service.getAlbumPortrait(pid, start, end, product);
}
} catch (Exception e) {
return null;
}
result.put("result", data);
return result;
}
}
When I request /cp/album it works and response data.
But I request /cp/usertop it throw an exception: NullPointException
reference service is null! service could not be null, IContentPortraitService is an interface and has only one implementation. And I absolutely sure I have scan service package and use #Service annotation on it's implementation.
Debug information:
When I request /cp/usertop:
ContentProtrationController instance is ContentPortraitServiceImpl$$EnhancerBySprinigCGLIB$bdfd5678#7591 and service is null
When I request /cp/album:
ContentProtrationController instance is ContentPortraitServiceImpl#7591 and service is not null, it works.
What's wrong with my code? This problem has troubled me for many days.Who knows how to solve this problem?

How to go from spring mvc multipartfile into zipinputstream

I have a Spring MVC controller that accepts a MultipartFile, which will be a zip file. The problem is I can't seem to go from that to a ZipInputStream or ZipFile, so that I can go through the entries. It either closes the stream prematurely, produces an empty file, or as in the case below, zipInputStream.getNextEntry() returning null.
This is my MVC controller:
#RequestMapping(value = "/content/general-import", method = RequestMethod.POST)
public ModelAndView handleGeneralUpload(
#RequestParam("file") MultipartFile file) throws IOException {
// hard code the signature for the moment
String signature = "RETAILER_GROUP:*|CHANNEL:*|LOCALE:de-AT|INDUSTRY:5499";
LOG.info("Processing file archive: {} with signature: {}.", file.getName(), signature);
ModelAndView mav = new ModelAndView();
mav.setViewName("contentUpload");
LOG.debug("File={} is empty={}.", file.getName(), file.isEmpty());
if (!file.isEmpty()) {
processFileZipEntry(file, signature);
mav.addObject("form", UploadViewModel.make("/content/general-import", "Updated content with file"));
return mav;
} else {
mav.addObject("form", UploadViewModel.make("/content/general-import", "Could not update content with file"));
return mav;
}
}
It delegates to the following method for processing:
protected void processFileZipEntry(MultipartFile file, String signature) throws IOException {
byte[] bytes = file.getBytes();
LOG.debug("Processing archive with bytes={}.", file.getBytes().length);
ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(bytes));
LOG.debug("Processing archive with size={}.", file.getSize());
ZipEntry entry = null;
while ((entry = zis.getNextEntry()) != null) {
LOG.debug("Processing file={} is directory?={}.", entry.getName(), entry.isDirectory());
// process each file, based on what it is and whether its a directory etc.
if (!entry.isDirectory()) {
// if the entry is a file, extract it
LOG.debug("Processing entry: {}",entry.getName());
int length = (int) entry.getSize();
Content contentToSave = null;
if(entry.getName().contains("gif")) {
contentToSave = Content.makeImage(entry.getName(), Content.GIF, signature, getBytesFrom(zis, "gif"));
} else if (entry.getName().contains("png")) {
contentToSave = Content.makeImage(entry.getName(), Content.PNG, signature, getBytesFrom(zis, "png"));
} else if (entry.getName().contains("jpeg")) {
contentToSave = Content.makeImage(entry.getName(), Content.JPEG, signature, getBytesFrom(zis, "jpeg"));
} else if (entry.getName().contains("json")) {
contentToSave = Content.makeFile(entry.getName(), Content.JSON, signature, getStringFrom(zis, length));
} else if (entry.getName().contains("js")) {
contentToSave = Content.makeFile(entry.getName(), Content.JS, signature, getStringFrom(zis, length));
} else if (entry.getName().contains("css")) {
contentToSave = Content.makeFile(entry.getName(), Content.CSS, signature, getStringFrom(zis, length));
}
Content contentAleadyThere = contentService.fetch(entry.getName());
if(contentAleadyThere != null) {
LOG.warn("Replacing file: {} with uploaded version.", contentToSave.getName());
}
contentService.put(contentToSave);
LOG.info("Persisted file: {} from uploaded version.", contentToSave.getName());
}
}
}
Basically, in this permutation, the file bytes are there, but there are no entries (zis.getNextEntry() does not exist. I can see that the zip file contains files, and the byte[] has about 3MB worth of stuff, so something must be going wrong with the streaming. Does anyone have a recipe for going from MultipartFile to ZipFile or ZipInputStream?
EDIT
To give you more information, I have a test harnass around this code, by using a MockMvc
#Test
public void testProcessingGeneralUpload() throws Exception {
Resource template = wac.getResource("classpath:lc_content/content.zip");
System.out.println("template content length: " + template.contentLength());
System.out.println("template path: " + template.getFile().getPath());
System.out.println("template filename: " + template.getFilename());
MockMultipartFile firstFile = new MockMultipartFile(
"file", "content.zip", MediaType.APPLICATION_OCTET_STREAM_VALUE, extractFile(template.getFile()));
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/content/general-import")
.file(firstFile))
.andExpect(status().isOk())
.andExpect(view().name("contentUpload"))
.andExpect(model().attributeExists("form")).andReturn();
// processing assertions
ModelMap modelMap = mvcResult.getModelAndView().getModelMap();
Object object = modelMap.get("form");
assertThat(object, is(not(nullValue())));
assertThat(object, is(instanceOf(UploadViewModel.class)));
UploadViewModel addModel = (UploadViewModel) object;
assertThat(addModel.getMessage(), is(notNullValue()));
assertThat(addModel.getPostUrl(), is(notNullValue()));
assertThat(addModel.getPostUrl(), is("/content/general-import"));
assertThat(addModel.getMessage(), is("Updated content with file"));
// persistence assertions
assertThat(contentDao.findByName("/content/control/basket-manager.js"), is(notNullValue()) );
}
The extractFile method is as follows:
private byte[] extractFile(File zipFile) throws IOException {
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
System.out.println("length of file: " + zipFile.length());
byte[] output = null;
try {
byte[] data = new byte[(int)zipFile.length()];
zipIn.read(data);
zipIn.close();
output = data;
} catch (IOException e) {
e.printStackTrace();
}
return output;
}
The length of bytes it produces is 3617817, which is the size I expect, and this is fed into the controller method at the top of this question.
I have continued working the problem. The size of the file is correct, it is a zipped file (it unpacks via the OS perfectly), and yet no ZipEntry enumeration.
I would for starters rewrite some of the code instead of doing things in memory with additional byte[].
You are using Spring's Resource class so why not simply use the getInputStream() method to construct the MockMultipartFile as you want to upload that file.
Resource template = wac.getResource("classpath:lc_content/content.zip");
MockMultipartFile firstFile = new MockMultipartFile(
"file", "content.zip", MediaType.APPLICATION_OCTET_STREAM_VALUE, template.getInputStream());
The same for your upload processing code the ZipInputStream can also be constructed on another InputStream which is also provided by the MultipartFile interface.
protected void processFileZipEntry(MultipartFile file, String signature) throws IOException {
LOG.debug("Processing archive with size={}.", file.getSize());
ZipInputStream zis = new ZipInputStream(file.getInputStream());
Wouldn't be the first time that jugling around with byte[] gives a problem. I also vaguely recall some issues with ZipInputStream which lead us to use ZipFile but for this you will first have to store the file in a temp directoy using the transferTo method on MultipartFile.
File tempFile = File.createTempFile("upload", null);
file.transferTo(tempFile);
ZipFile zipFile = new ZipFle(tempFile);
// Proces Zip
tempFile.delete();

JasperReports: Calling report from servlet [duplicate]

This question already has answers here:
JasperReports: How to call the report in jsp page
(6 answers)
Closed 6 years ago.
I'm new to JasperReports and dont know how to call jasper file from servlet. My report contains the pie chart.
You can prepare the Jasper file and stream it to the client.
bytes[] byteStream = JasperRunManager.runReportToPdf("myJasperReport.jasper",paramMap,databaseConn);
OutputStream outStream = servletResponse.getOutputStream();
response.setHeader("Content-Disposition","inline, filename=myReport.pdf");
response.setContentType("application/pdf");
response.setContentLength(byteStream.length);
outStream.write(bytes,0,bytes.length);
Here is a dummy report created within a Servlet file.
It is the same as it would be in normal Java class.
Just make sure you have the imports for your jasper report classes at the top of the file.
The bellow example builds a report from an XML datasource.
public class JasperServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
String reportFile = "myJasperReport.jrxml";
File outputFile = new File("Report.pdf");
HashMap hm = new HashMap();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory
.newDocumentBuilder();
Document document = documentBuilder.parse(new File("myXml.xml"));
// Compile the report
JasperReport report = JasperCompileManager
.compileReport(reportFile);
JRXmlDataSource xml = new JRXmlDataSource(document, "/xml/root");
// Fill the report
JasperPrint print = JasperFillManager.fillReport(report, hm, xml);
// Create an Exporter
JRExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.OUTPUT_FILE, outputFile);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
// Export the file
exporter.exportReport();
} catch (Exception e) {
e.printStackTrace();
}
}
}
A complete way to do this from the servlet would be:
public void myServletMethod(HttpServletRequest request, HttpServletResponse response) throws IOException{
JasperReport jasperReport = null;
JasperDesign jasperDesign = null;
Map parameters = new HashMap();
String path = getServletContext().getRealPath("/WEB-INF/");
jasperDesign = JRXmlLoader.load(path+"/relative/path/to/MyReport.jrxml");
jasperReport = JasperCompileManager.compileReport(jasperDesign);
byte[] byteStream = JasperRunManager.runReportToPdf(jasperReport, parameters, **new DataSourceOfYourPreference**);
OutputStream outStream = response.getOutputStream();
response.setHeader("Content-Disposition","inline, filename=myReport.pdf");
response.setContentType("application/pdf");
response.setContentLength(byteStream.length);
outStream.write(byteStream,0,byteStream.length);
}

Resources