Thymeleaf img not calling spring controler - spring

Here is my gradle dependencies:
dependencies {
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("org.springframework.boot:spring-boot-starter-security")
compile("org.springframework:spring-jdbc:4.1.0.RELEASE")
compile("org.springframework.boot:spring-boot-starter-data-jpa")
compile("mysql:mysql-connector-java:5.1.+")
compile("org.webjars:bootstrap:3.0.3")
compile("org.webjars:jquery:2.0.3-1")
compile("org.springframework.security.oauth:spring-security-oauth2:2.0.7.RELEASE")
compile("org.springframework.security:spring-security-test:4.0.0.RELEASE")
compile("org.thymeleaf:thymeleaf-spring4")
compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect")
compile("org.springframework.boot:spring-boot-starter-web")
compile("com.google.code.gson:gson:2.2.4")
compile("javax.mail:mail:1.4.5")
compile("org.springframework:spring-context-support:3.2.2.RELEASE")
compile("org.apache.commons:commons-io:1.3.2")
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
testCompile("junit:junit")
}
I have defined a method in my controller:
#ResponseBody
#RequestMapping(value = "/mainMenu/companyOfficeMainMenu/imagetest/{server_image_id}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto(#PathVariable("server_image_id") Long server_image_id) throws IOException {
Image notUpdatedImage = mobileManagment.getImage(server_image_id);
String locationRoot = env.getProperty("location.sever.root");
String locationOfCompanyData = env.getProperty("location.compay.data");
String locationOfImage = env.getProperty("location.compay.media.images");
String storeImageName =
locationOfCompanyData
+ File.separator
+ locationOfImage
+ File.separator
+ notUpdatedImage.getCompany_id()
+ File.separator +
+ notUpdatedImage.getServer_questionnaire_attempt_key()
+ File.separator
+ notUpdatedImage.getImage_name();
File uploadedFile = new File(locationRoot, storeImageName);
InputStream inputStream = new FileInputStream(uploadedFile.getAbsolutePath());
return IOUtils.toByteArray(inputStream);
}
And in Thymeleaf, I try to call it:
<img th:src="#{/mainMenu/companyOfficeMainMenu/imagetest/${object.getServer_image_id()}}" />
I have a break point in the method in the controller but it's not being called.
Here is also another method that does not get called:
#RequestMapping(value = "/mainMenu/companyOfficeMainMenu/image/{server_image_id}", method = RequestMethod.GET)
public ResponseEntity<byte[]> getImage(#PathVariable("server_image_id") Long server_image_id) throws IOException {
Image notUpdatedImage = mobileManagment.getImage(server_image_id);
String locationRoot = env.getProperty("location.sever.root");
String locationOfCompanyData = env.getProperty("location.compay.data");
String locationOfImage = env.getProperty("location.compay.media.images");
String storeImageName =
locationOfCompanyData
+ File.separator
+ locationOfImage
+ File.separator
+ notUpdatedImage.getCompany_id()
+ File.separator +
+ notUpdatedImage.getServer_questionnaire_attempt_key()
+ File.separator
+ notUpdatedImage.getImage_name();
File uploadedFile = new File(locationRoot, storeImageName);
InputStream inputStream = new FileInputStream(uploadedFile.getAbsolutePath());
byte[] imageContent = IOUtils.toByteArray(inputStream);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
return new ResponseEntity<byte[]>(imageContent, headers, HttpStatus.OK);
}
#ResponseBody
#RequestMapping(value = "/mainMenu/companyOfficeMainMenu/imagetest/{server_image_id}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto(#PathVariable("server_image_id") Long server_image_id) throws IOException {
Image notUpdatedImage = mobileManagment.getImage(server_image_id);
String locationRoot = env.getProperty("location.sever.root");
String locationOfCompanyData = env.getProperty("location.compay.data");
String locationOfImage = env.getProperty("location.compay.media.images");
String storeImageName =
locationOfCompanyData
+ File.separator
+ locationOfImage
+ File.separator
+ notUpdatedImage.getCompany_id()
+ File.separator +
+ notUpdatedImage.getServer_questionnaire_attempt_key()
+ File.separator
+ notUpdatedImage.getImage_name();
File uploadedFile = new File(locationRoot, storeImageName);
InputStream inputStream = new FileInputStream(uploadedFile.getAbsolutePath());
return IOUtils.toByteArray(inputStream);
}
When I press f12 on the screen I can see the output of the image tag:
<img src="/mainMenu/companyOfficeMainMenu/image/${object.getServer_image_id()}">
That does not look right.
When I output I get 27 (which is correct)
<p th:text="${object.getServer_image_id()}"></p>

You're not using the Thymeleaf Link URL syntax correctly. You need to specify a parameter in braces (similar to the #RequestMapping) eg. {server_image_id}. Then you specify the value to replace it with afterwards between parenthesis (server_image_id=${object.getServer_image_id()}).
All together:
<img th:src="#{/mainMenu/companyOfficeMainMenu/imagetest/{server_image_id}(server_image_id=${object.getServer_image_id()})}" />

Related

How to download a large file in a Spring Boot microservices application?

I am trying to download a large file in a Spring Boot microservices application. Can anyone suggest a way of doing that?
Here is my front-end code
<a href={path + curDoc.id} download></a>
AJAX controller code
#GetMapping("/download-collector-file/{collectorFileId}")
public ResponseEntity<Resource> downloadCollectorFile(#PathVariable String collectorFileId) {
System.out.println("kjwenfjkewew beforr");
ResponseEntity<Resource> r= fileServiceAPI.downloadCollectorFile("token",collectorFileId, false);
System.out.println("after api");
return r;
}
Feign client code
#GetMapping("/order-files/read/{id}")
ResponseEntity<Resource> downloadCollectorFile(#RequestHeader("Authorization") String auth,
#PathVariable String id,
#RequestParam("isDownload") Boolean isDownload);
And my service back-end API code
#RequestMapping(value="/{id}" , method = RequestMethod.GET )
public ResponseEntity<InputStreamResource> downloadCollectorFile(#RequestHeader("Authorization") String auth, #PathVariable String id, #RequestParam(required = false, value = "isDownload") boolean isDownload) throws TgxValidationException, IOException {
System.out.println("new file id------===>"+id);
Optional<TgxFilesEntity> optionalTgxFilesEntity = tgxFilesRepository.findByIdAndDeletedFalse(id);
if (optionalTgxFilesEntity.isPresent()) {
TgxFilesEntity tgxFilesEntity = optionalTgxFilesEntity.get();
logger.info(">> UPLOAD_FOLDER=" + UPLOAD_FOLDER_PATH);
String absolutePath = UPLOAD_FOLDER_PATH + "/collector/" + tgxFilesEntity.getRelationalId() + "/";
final File parent = new File(absolutePath + tgxFilesEntity.getFilename());
InputStreamResource resource = new InputStreamResource(new FileInputStream(parent));
String mimeType = URLConnection.guessContentTypeFromName(tgxFilesEntity.getFilename());
logger.info("mimeType" + mimeType);
HttpHeaders headers = new HttpHeaders();
if (!isDownload) {
headers.add("Content-disposition", "inline; filename=" + tgxFilesEntity.getFilename());
if (mimeType == null) {
int lastIndexOf = tgxFilesEntity.getFilename().lastIndexOf(".");
if (tgxFilesEntity.getFilename().substring(lastIndexOf).contains(".json")) {
mimeType = "application/json";
} else if (tgxFilesEntity.getFilename().substring(lastIndexOf).contains(".xlsx")) {
mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
} else if (tgxFilesEntity.getFilename().substring(lastIndexOf).contains(".doc")) {
mimeType = "application/msword";
}
else if (tgxFilesEntity.getFilename().substring(lastIndexOf).contains(".zip")) {
mimeType = "application/zip";
}
else {
mimeType = "text/plain";
}
}
} else {
logger.info("hello else");
headers.add("Content-disposition", "attachment; filename=" + tgxFilesEntity.getFilename());
mimeType = "multipart/form-data";
}
System.out.println("brefore return===>"+resource.getFilename());
return ResponseEntity.ok().headers(headers).contentType(MediaType.parseMediaType(mimeType)).body(resource);
} else throw new FileNotFoundException(environment.getProperty("tgx.validation.file_not_found"));
}
Basically, it is not working for larger files like (300mb,400mb).
Is there any better approach of doing this?

Sending objects in a get request

I 'll explain first what I'm trying to do:
There's a service method that receives a thymeleaf template html file, process that and then transform into a pdf. The job that was assigned to me is to create an endpoint which returns the template html so the service will call that endpoint to get the html.
I don't know how to pass objects in a get request.
The code in the service method before:
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
Context context = new Context();
context.setVariable("expenseReportPdf", expenseReportPdf);
context.setVariable("expensePdf", expensePdfList);
context.setVariable("expenseImg", jpgFile);
context.setVariable("amountCompanyCurrency", amountCompanyCurrency);
context.setVariable("expenseIncurredList", expenseIncurredList);
context.setVariable("expenseRiepiloghiList",expenseRiepiloghiList);
context.setVariable("advancePayBigDecimal", advancePayBigDecimal);
context.setVariable("dailyAllowanceList", dailyAllowanceList);
context.setVariable("dailyAllowanceFlag", dailyAllowanceFlag.booleanValue());
context.setVariable("logo",logo);
context.setVariable("logoSmartex",logoSmartex);
logger.debug("Logo Smartex:" + logoSmartex);
logger.debug("Logo Company:" + logo);
String renderedHtmlContent = templateEngine.process("template", context);
Firstly I moved that part in a configuration class which creates the beans necessary to return the html.
#Configuration
public class TemplateConfiguration {
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(htmlTemplateResolver2());
return templateEngine;
}
// Esiste giĆ  un bean che si chiama htmlTemplateResolver
#Bean
public ClassLoaderTemplateResolver htmlTemplateResolver2() {
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setOrder(Integer.valueOf(3));
resolver.setPrefix("templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
}
Then i create the endpoint which should return the html processed.
#GetMapping(path = "/get-template-html")
public String getTemplateHTMLEndpoint(#RequestParam("expenseReportPdf") String expenseReportPdfJSON, #RequestParam("expensePdfList") String expensePdfListJSON,
#RequestParam("jpgFile") String jpgFileJSON, #RequestParam("amountCompanyCurrency") String amountCompanyCurrencyJSON,
#RequestParam("expenseIncurredList") String expenseIncurredListJSON, #RequestParam("expenseRiepiloghiList") String expenseRiepiloghiListJSON,
#RequestParam("advancePayBigDecimal") String advancePayBigDecimalJSON, #RequestParam("dailyAllowanceList") String dailyAllowanceListJSON,
#RequestParam("dailyAllowanceFlag") String dailyAllowanceFlag, #RequestParam("logo") String logo, #RequestParam("logoSmartex") String logoSmartex) {
// TODO convert JSON params to relative objects
Context context = new Context();
context.setVariable("expenseReportPdf", expenseReportPdf);
context.setVariable("expensePdf", expensePdfList);
context.setVariable("expenseImg", jpgFile);
context.setVariable("amountCompanyCurrency", amountCompanyCurrency);
context.setVariable("expenseIncurredList", expenseIncurredList);
context.setVariable("expenseRiepiloghiList",expenseRiepiloghiList);
context.setVariable("advancePayBigDecimal", advancePayBigDecimal);
context.setVariable("dailyAllowanceList", dailyAllowanceList);
context.setVariable("dailyAllowanceFlag", String dailyAllowanceFlag);
context.setVariable("logo",logo);
context.setVariable("logoSmartex",logoSmartex);
String renderedHtmlContent = templateEngine.process("template", context);
return renderedHtmlContent;
}
}
Finally I created a method in the service which calls the endpoint.
private String callGetTemplateHTMLEndPoint(ExpenseReportPdf expenseReportPdf, List<ExpensePdf> expensePdfList, List<ExpenseImg> jpgFile,
BigDecimal amountCompanyCurrency, List<ExpenseIncurred> expenseIncurredList,
List<ExpenseRiepiloghi> expenseRiepiloghiList, BigDecimal advancePayBigDecimal,
List<DailyAllowanceDetails> dailyAllowanceList, Boolean dailyAllowanceFlag, String logo,
String logoSmartex) {
ObjectMapper objectMapper = new ObjectMapper();
String JSONExpenseReportPdf = "";
String JSONExpensePdfList = "";
String JSONJpgFile = "";
String JSONAmountCompanyCurrency = "";
String JSONExpenseIncurredList = "";
String JSONExpenseRiepiloghiList = "";
String JSONAdvancePayBigDecimal = "";
String JSONDailyAllowanceList = "";
// Trasformo i parametri in JSON
try {
JSONExpenseReportPdf = objectMapper.writeValueAsString(expenseReportPdf);
JSONExpensePdfList = objectMapper.writeValueAsString(expensePdfList);
JSONJpgFile = objectMapper.writeValueAsString(jpgFile);
JSONAmountCompanyCurrency = objectMapper.writeValueAsString(amountCompanyCurrency);
JSONExpenseIncurredList = objectMapper.writeValueAsString(expenseIncurredList);
JSONExpenseRiepiloghiList = objectMapper.writeValueAsString(expenseRiepiloghiList);
JSONAdvancePayBigDecimal = objectMapper.writeValueAsString(advancePayBigDecimal);
JSONDailyAllowanceList = objectMapper.writeValueAsString(dailyAllowanceList);
} catch (JsonProcessingException e1) {
e1.printStackTrace();
}
// Creo i query params coi JSON
String params = "?";
params += "expenseReportPdf=" + JSONExpenseReportPdf + "&";
params += "expensePdfList=" + JSONExpensePdfList + "&";
params += "jpgFile=" + JSONJpgFile + "&";
params += "amountCompanyCurrency=" + JSONAmountCompanyCurrency + "&";
params += "expenseIncurredList=" + JSONExpenseIncurredList + "&";
params += "expenseRiepiloghiList=" + JSONExpenseRiepiloghiList + "&";
params += "advancePayBigDecimal=" + JSONAdvancePayBigDecimal + "&";
params += "dailyAllowanceList=" + JSONDailyAllowanceList + "&";
params += "dailyAllowanceFlag=" + dailyAllowanceFlag + "&";
params += "logo=" + logo + "&";
params += "logoSmartex=" + logoSmartex;
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:9898/Smartex/expense-report-pdf/get-template-html" + params))
.build();
String templateHTML = "Problems with the request";
try {
templateHTML = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString())
.body();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return templateHTML;
}
I don't know how to send/receive the params needed for the processing of the template, any idea?
TY
After a while I thought I could transform objects into JSON, add them as query params and then transform them back in the controller but there are 2 problems:
The URL is too much long (2568 characters)
URL contains {} and give error

how to write code for viewing s3 bucket image by spring boot api

I write code for download
#GetMapping(value= "/download/{fileName}")
public ResponseEntity<ByteArrayResource> downloadFile(#PathVariable String fileName) {
final byte[] data = amazonClient.downloadFile(fileName);
final ByteArrayResource resource = new ByteArrayResource(data);
return ResponseEntity
.ok()
.contentLength(data.length)
.header("Content-type", "application/octet-stream")
.header("Content-disposition", "attachment; filename=\"" + fileName + "\"")
.body(resource);
}
and the service method for that : -
public byte[] downloadFile(final String fileName) {
byte[] content = null;
logger.info("Downloading an object with key= " + fileName);
final S3Object s3Object = s3client.getObject(bucketName, fileName);
final S3ObjectInputStream stream = s3Object.getObjectContent();
try {
content = IOUtils.toByteArray(stream);
logger.info("File downloaded successfully.");
s3Object.close();
} catch(final IOException ex) {
logger.info("IO Error Message= " + ex.getMessage());
}
return content;
}
but I want to code for the only view not for download.
You can try this way...
AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, key));
InputStream objectData = object.getObjectContent();
BufferedImage bf = ImageIO.read(objectData);
using javax.imageio

upload file using rest services in spring mvc

I want to upload a file( any type of file ) into a forlder using web services and spring mvc so I have a sever side and a client side.
On my client side this is the code
#RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST , produces="application/json")
public #ResponseBody
Boolean uploadMultipleFileHandler(
#RequestParam("name") MultipartFile[] files) {
MailService ms= new MailService();
Map<String, List<ByteArrayResource>>rval = new HashMap<String, List<ByteArrayResource>>();
String message = "";
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
List<Object> files1 = new ArrayList<>();
List<Object> files2 = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
System.out.println(file.getOriginalFilename());
try {
byte[] bytes = file.getBytes();
files1.add(new ByteArrayResource(bytes));
files2.add(file.getOriginalFilename());
//System.out.println(map.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
map.put("files", files1);
map.put("names", files2);
System.out.println(map.get("files").toString());
RestTemplate restTemplate = new RestTemplate();
String SERVER_URI="http://localhost:8080/BackEndFinalVersion";
Boolean p=restTemplate.postForObject(SERVER_URI+"/uploadMultipleFile", map, Boolean.class);
System.out.println(p.toString());
//message = message + ms.encodeFileToBase64Binary( bytes);
//rval.put("success",message);
return true;
}
and the server side code is
#RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody Boolean uploadMultipleFileHandler(#RequestParam("files") List<Object> files , #RequestParam("names") List<Object> names) {
//MailService ms= new MailService();
//Map<String, Object> rval = new HashMap<String, Object>();
String message = "";
System.out.println("looool");
System.out.println(files);
System.out.println(names);
//System.out.println(files.get(0).toString());
for (int i = 0; i < files.size(); i++) {
System.out.println(files.get(i).getClass());
String file = (String)files.get(i);
try {
byte[] bytes = file.getBytes();
//FileUtils.writeStringToFile(new File("log.txt"), file, Charset.defaultCharset());
// Creating the directory to store file
String rootPath = "C:/Users/Wassim/Desktop/uploads";
File dir = new File(rootPath);
if (!dir.exists())
dir.mkdirs();
File serverFile = new File(dir.getAbsolutePath() + File.separator + ( names.get(i)));
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
//message = message + "You successfully uploaded file=" + ( (MultipartFile) files.get(i)).getOriginalFilename() + "<br />";
//FileUtils.writeByteArrayToFile(new File(dir.getAbsolutePath() + File.separator + files.get(i).getOriginalFilename()), ms.decodeFileToBase64Binary(ms.encodeFileToBase64Binary( bytes)));
//rval.put("success"+i, message);
System.out.println("noooo");
} catch (Exception e) {
message += "You failed to upload " + " => " + e.getMessage();
//rval.put("error", message);
return false;
}
}
return true;
My problem is that this code doesn't work only with .txt files
can any one support me ??

Trying to upload MultipartFile with postman

I am trying to upload a Multipart File using PostMan and getting errors. Here is the code and screenshots:
http://imgur.com/pZ5cXrh
http://imgur.com/NaWQceO
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public void uploadFileHandler(#RequestParam("name") String name,
#RequestParam("name") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
//String rootPath = System.getProperty("catalina.home");
String rootPath = "C:\\Desktop\\uploads";
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location="
+ serverFile.getAbsolutePath());
System.out.println("You successfully uploaded file=" + name);
} catch (Exception e) {
System.out.println("You failed to upload " + name + " => " + e.getMessage());
}
} else {
System.out.println("You failed to upload " + name
+ " because the file was empty.");
}
}
You should have a thing like this:
#RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = "multipart/form-data")
public void uploadFileHandler(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
//String rootPath = System.getProperty("catalina.home");
String rootPath = "C:\\Users\\mworkman02\\Desktop\\uploads";
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
System.out.println("Server File Location="
+ serverFile.getAbsolutePath());
System.out.println("You successfully uploaded file=" + name);
} catch (Exception e) {
System.out.println("You failed to upload " + name + " => " + e.getMessage());
}
} else {
System.out.println("You failed to upload " + name
+ " because the file was empty.");
}
}
Please pay attention to consumes = "multipart/form-data". It is necessary for your uploaded file because you should have a multipart call. You should have #RequestParam("file") MultipartFile file instead of #RequestParam("name") MultipartFile file).
Of course you should have configured a multipartview resolver the built-in support for apache-commons file upload and native servlet 3.

Resources