Map a image file through Spring controller - java

Is there any way to map a image file using a spring controller? In my spring application, I want store the images in the directory src/main/resources (i'm using maven) and access them with a method like this:
#RequestMapping(value="image/{theString}")
public ModelAndView image(#PathVariable String theString) {
return new ModelAndView('what should be placed here?');
}
the string theString it's the image name (without extension). With this approach, I should be able to access my images this way:
/webapp/controller_mapping/image/image_name
Anyone can point a direction to do that?

You can return HttpEntity<byte[]>. Construct new instance providing image byte array and necessary headers like content length and mime type then return it from your method. Image bytes can be obtained using classloader getResourceAsStream method.

This works for me. It could use some cleaning up but it works. The ServiceException is just a simple base exception.
Good Luck!
package com.dhargis.example;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/image")
public class ImageController {
private static final Logger log = Logger.getLogger(ImageController.class);
private String filestore = "C:\\Users\\dhargis";
//produces = "application/octet-stream"
#RequestMapping(value = "/{filename:.+}", method = RequestMethod.GET)
public void get( #PathVariable String filename,
HttpServletRequest request,
HttpServletResponse response) {
log.info("Getting file " + filename);
try {
byte[] content = null;
File store = new File(filestore);
if( store.exists() ){
File file = new File(store.getPath()+File.separator+filename);
if( file.exists() ){
content = FileUtils.readFileToByteArray(file);
} else {
throw new ServiceException("File does not exist");
}
} else {
throw new ServiceException("Report store is required");
}
ServletOutputStream out = response.getOutputStream();
out.write(content);
out.flush();
out.close();
} catch (ServiceException e) {
log.error("Error on get", e);
} catch (IOException e) {
log.error("Error on get", e);
}
}
}
<!-- begin snippet: js hide: false -->

Related

Spring Boot REST API return list of files

I am trying to return a list of files from a directory. Here's my code:
package com.demo.web.api.file;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.demo.core.Logger;
import io.swagger.v3.oas.annotations.Operation;
#RestController
#RequestMapping(value = "/files")
public class FileService {
private static final Logger logger = Logger.factory(FileService.class);
#Value("${file-upload-path}")
public String DIRECTORY;
#Value("${file-upload-check-subfolders}")
public boolean CHECK_SUBFOLDERS;
#GetMapping(value = "/list")
#Operation(summary = "Get list of Uploaded files")
public ResponseEntity<List<File>> list() {
List<File> files = new ArrayList<>();
if (CHECK_SUBFOLDERS) {
// Recursive check
try (Stream<Path> walk = Files.walk(Paths.get(DIRECTORY))) {
List<Path> result = walk.filter(Files::isRegularFile).collect(Collectors.toList());
for (Path p : result) {
files.add(p.toFile().getAbsoluteFile());
}
} catch (Exception e) {
logger.error(e.getMessage());
}
} else {
// Checks the root directory only.
try (Stream<Path> walk = Files.walk(Paths.get(DIRECTORY), 1)) {
List<Path> result = walk.filter(Files::isRegularFile).collect(Collectors.toList());
for (Path p : result) {
files.add(p.toFile().getAbsoluteFile());
}
} catch (Exception e) {
logger.error(e.getMessage());
}
}
return ResponseEntity.ok().body(files);
}
}
As seen in the code, I am trying to return a list of files.
However, when I test in PostMan, I get a list of string instead.
How can I make it return the file object instead of the file path string? I need to get the file attributes (size, date, etc.) to display in my view.
I would recommend that you change your ResponseEntity<> to return not a List of File but instead, a List of Resource, which you can then use to obtain the file metadata that you need.
public ResponseEntity<List<Resource>> list() {}
You can also try specifying a produces=MediaType... param in your #GetMapping annotation so as to tell the HTTP marshaller which kind of content to expect.
You'd have to Create a separate payload with the details you wanna respond with.
public class FilePayload{
private String id;
private String name;
private String size;
public static fromFile(File file){
// create FilePayload from File object here
}
}
And convert it using a mapper from your internal DTO objects to payload ones.
final List<FilePayload> payload = files.forEach(FilePayload::fromFile).collect(Collectors.toList());
return new ResponseEntity<>(payload, HttpStatus.OK);
I think you should not return a body in this case as you may be unaware of the size.
Better to have another endpoint to GET /files/{id}
I did give this another thought. What I just needed was the filename, size and date of the file. From there, I can get the file extension and make my list display look good already.
Here's the refactored method:
#GetMapping(value = "/list")
#Operation(summary = "Get list of Uploaded files")
public ResponseEntity<String> list() {
JSONObject responseObj = new JSONObject();
List<JSONObject> files = new ArrayList<>();
// If CHECK_SUBFOLDERS is true, pass MAX_VALUE to make it recursive on all
// sub-folders. Otherwise, pass 1 to use the root directory only.
try (Stream<Path> walk = Files.walk(Paths.get(DIRECTORY), CHECK_SUBFOLDERS ? MAX_VALUE : 1)) {
List<Path> result = walk.filter(Files::isRegularFile).collect(Collectors.toList());
for (Path p : result) {
JSONObject file = new JSONObject();
file.put("name", p.toFile().getName());
file.put("size", p.toFile().length());
file.put("lastModified", p.toFile().lastModified());
files.add(file);
}
responseObj.put("data", files);
} catch (Exception e) {
String errMsg = CoreUtils.formatString("%s: Error reading files from the directory: \"%s\"",
e.getClass().getName(), DIRECTORY);
logger.error(e, errMsg);
responseObj.put("errors", errMsg);
}
return ResponseEntity.ok().body(responseObj.toString());
}
The above was what I ended up doing. I created a JSONObject of the props I need, and then returned the error if it did not succeed. This made it a lot better for me.

Java Spring - Can't save image to static folder

I want to save image to resources/static/photos file, but Java/Kotlin can't find it. It finds project/photos well though.
This is a code, in Kotlin, but I don't think it matters
override fun saveImage(imageFile: MultipartFile, id: String) {
val bytes = imageFile.bytes
val path = Paths.get(
"$imagesFolderPath$id.${imageFile.originalFilename.substringAfter('.')}")
Files.write(path, bytes)
}
I need this to be saved to resources/static/photos to be able to access it from thymeleaf.
Thanks.
The problem is, you may be able to save files inside your projects directory during the development phase, but that won't be possible as soon as you export your project as an application package (a .jar-application, .war-archive etc), because at that point, everything that previously was an actual directory on your file-system is now a single file.
Here's an example how you could implement this by saving the images in a configurable folder:
I never wrote a line of code in Kotlin. I hope this example helps you even if it is in Java.
This is an example controller that accepts images to be uploaded on a POST endpoint and being downloaded on a GET endpoint:
package example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Optional;
#RestController
public class MyController {
private final Path imageStorageDir;
/*
The target path can be configured in the application.properties / application.yml or using the parameter -Dimage-storage.dir=/some/path/
*/
#Autowired
public MyController(#Value("${image-storage-dir}") Path imageStorageDir) {
this.imageStorageDir = imageStorageDir;
}
#PostConstruct
public void ensureDirectoryExists() throws IOException {
if (!Files.exists(this.imageStorageDir)) {
Files.createDirectories(this.imageStorageDir);
}
}
/*
This enables you to perform POST requests against the "/image/YourID" path
It returns the name this image can be referenced on later
*/
#PostMapping(value = "/image/{id}", produces = MediaType.TEXT_PLAIN_VALUE)
public String uploadImage(#RequestBody MultipartFile imageFile, #PathVariable("id") String id) throws IOException {
final String fileExtension = Optional.ofNullable(imageFile.getOriginalFilename())
.flatMap(MyController::getFileExtension)
.orElse("");
final String targetFileName = id + "." + fileExtension;
final Path targetPath = this.imageStorageDir.resolve(targetFileName);
try (InputStream in = imageFile.getInputStream()) {
try (OutputStream out = Files.newOutputStream(targetPath, StandardOpenOption.CREATE)) {
in.transferTo(out);
}
}
return targetFileName;
}
/*
This enables you to download previously uploaded images
*/
#GetMapping("/image/{fileName}")
public ResponseEntity<Resource> downloadImage(#PathVariable("fileName") String fileName) {
final Path targetPath = this.imageStorageDir.resolve(fileName);
if (!Files.exists(targetPath)) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(new PathResource(targetPath));
}
private static Optional<String> getFileExtension(String fileName) {
final int indexOfLastDot = fileName.lastIndexOf('.');
if (indexOfLastDot == -1) {
return Optional.empty();
} else {
return Optional.of(fileName.substring(indexOfLastDot + 1));
}
}
}
Let's say you uploaded am image with the file-ending .png and the id HelloWorld, you could then access the image using the url:
http://localhost:8080/image/HelloWorld.png
Using this URL you can also reference the image in any of your thymeleaf templates:
<img th:src="#{/image/HelloWorld.png}"></img>

Fetch thymeleaf fragments from external URL

I have a spring-boot/thymeleaf website on server A, and I want to load some fragments from server B. The fragments are dynamic and some of them call java methods defined in server A, so what I need is to fetch those fragments (as plain text?) from server B and include them in my html pages in server A, where they will be processed etc. Server B will act like a repository, it won't do any processing at all, just serve the fragments to server A.
Is this possible?
Ok, I posted this question because all my attempts were failing, but after all it was just a typo that was holding me back... So here's what worked for me, in case anyone is interested:
I saved the fragments in src/main/resources/static/fragments on server B. Let's assume a file named frg with a fragment called "content" inside it.
I created a controller in server B to serve the files as plain text, like this:
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.File;
import java.nio.file.Files;
import javax.servlet.http.HttpServletResponse;
#Controller
public class FragmentsController {
#RequestMapping(value = "/fragments/{fragmentPage}")
#ResponseBody
public String GetFragment (#PathVariable String fragmentPage, HttpServletResponse response) throws Exception {
response.setHeader("Content-Type", "text/plain");
response.setHeader("success", "no");
if (fragmentPage == null)
{
System.err.println("Nothing to serve!");
return null;
}
System.out.println("Serving fragment: " + fragmentPage);
String fileName = "static/fragments/"+fragmentPage;
File resource = new ClassPathResource(fileName).getFile();
String frg = "";
try
{
frg= new String(Files.readAllBytes(resource.toPath()));
response.setHeader("success", "yes");
}
catch (Exception e)
{
frg = "Error loading fragment: " + e.getMessage();
}
return frg;
}
}
From server A, I can now fetch the fragment like this:
<div th:include="http://<server_b_url:port>/fragments/frg :: content"></div>

java.io.FileNotFoundException: (The system cannot find the file specified) when using multipart

package com.act.webmail.service;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.act.webmail.dto.MessageToSend;
#Service
public class ActMailSenderService {
#Autowired
private JavaMailSender javaMailSender;
#Async
public void sendEmail(MessageToSend messageToSend, MultipartFile... multipartFileList) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
if (messageToSend.getReplyTo() != null && !messageToSend.getReplyTo().equals("")){
mimeMessage.addHeader("In-Reply-To", messageToSend.getReplyTo());
}
helper.setFrom("jackson.baby#xxxx.in");
helper.setTo(messageToSend.getTo());
helper.setSubject(messageToSend.getSubject());
helper.setText(messageToSend.getBody(), true);
for (MultipartFile multipartFile : multipartFileList) {
byte[] multipartFileByteArray= multipartFile.getBytes();
helper.addAttachment(multipartFile.getOriginalFilename(), new ByteArrayResource(multipartFileByteArray));
}
javaMailSender.send(mimeMessage);
System.out.println(messageToSend.getReplyTo() + " sent successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I initialised new ByteArrayResource(multipartFile.getBytes()) and used in addAttachment function of org.springframework.mail.javamail.MimeMessageHelper but i'm getting an exception "java.io.FileNotFoundException: C:\Users\Jackson Baby\AppData\Local\Temp\tomcat.8088819519816892725.8080\work\Tomcat\localhost\ROOT\upload_525fd01b_db90_4589_921f_50bf9a1e6e47_00000001.tmp (The system cannot find the file specified)"
is there any way to solve this issue?
I had the same issue where when I would try to the get the bytes or input stream of the file; I would be getting File Not Found Exception.
I finally solved it by removing the #Async Annotation from the Rest Controller Method.
That seemed to be creating the issue...

Convert DOCX to HTML incliding IMAGES

I am using DOCX4J to convert the DOCX to HTML .I have successfully done the conversion and got the html format.I will be using the html format to embed it as EMAIL body to send an email.But I have some issues which are listed below....
Unable to display images in email body
Losing the spaces and bullets
Please find the code which I have written,
WordprocessingMLPackage wordMLPackage;
wordMLPackage = Docx4J.load(new java.io.File(resourcePath2));
HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
htmlSettings.setImageDirPath(imageFolder + resourcePath2 + "_files");
htmlSettings.setImageTargetUri(imageFolder +resourcePath2.substring(resourcePath2.lastIndexOf("/")+1) + "_files");
htmlSettings.setWmlPackage(wordMLPackage);
OutputStream os;
os = new ByteArrayOutputStream();
Docx4jProperties.setProperty("docx4j.Convert.Out.HTML.OutputMethodXML", true);
Docx4J.toHTML(htmlSettings, os, Docx4J.FLAG_SAVE_FLAT_XML);
DOCX = ((ByteArrayOutputStream)os).toString();
You may add like this in your code
package tcg.doc.web.managedBeans;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component
#Scope("session")
#Qualifier("ConvertWord")
public class ConvertWord {
private static final String docName = "TestDocx.docx";
private static final String outputlFolderPath = "d:/";
String htmlNamePath = "docHtml.html";
String zipName="_tmp.zip";
File docFile = new File(outputlFolderPath+docName);
File zipFile = new File(zipName);
public void ConvertWordToHtml() {
try {
// 1) Load DOCX into XWPFDocument
InputStream doc = new FileInputStream(new File(outputlFolderPath+docName));
System.out.println("InputStream"+doc);
XWPFDocument document = new XWPFDocument(doc);
// 2) Prepare XHTML options (here we set the IURIResolver to load images from a "word/media" folder)
XHTMLOptions options = XHTMLOptions.create(); //.URIResolver(new FileURIResolver(new File("word/media")));;
// Extract image
String root = "target";
File imageFolder = new File( root + "/images/" + doc );
options.setExtractor( new FileImageExtractor( imageFolder ) );
// URI resolver
options.URIResolver( new FileURIResolver( imageFolder ) );
OutputStream out = new FileOutputStream(new File(htmlPath()));
XHTMLConverter.getInstance().convert(document, out, options);
System.out.println("OutputStream "+out.toString());
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
}
public static void main(String[] args) {
ConvertWord cwoWord=new ConvertWord();
cwoWord.ConvertWordToHtml();
System.out.println();
}
public String htmlPath(){
// d:/docHtml.html
return outputlFolderPath+htmlNamePath;
}
public String zipPath(){
// d:/_tmp.zip
return outputlFolderPath+zipName;
}
}
For maven Dependency on pom.xml
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>
<version>1.0.4</version>
</dependency>
or download it from Here
For images to work in an email body, I guess you need to use either a data URI or publish them to a web-reachable location.
In either case, you'll need to write an implementation of:
public interface ConversionImageHandler {
/**
* #param picture
* #param relationship of the image
* #param part of the image, if it is an internal image, otherwise null
* #return uri for the image we've saved, or null
* #throws Docx4JException this exception will be logged, but not propagated
*/
public String handleImage(AbstractWordXmlPicture picture, Relationship relationship, BinaryPart part) throws Docx4JException;
}
and configure docx4j to use it with htmlSettings.setImageHandler.
You can look at some of the existing implementations in the docx4j source code, and take advantage of the helper methods in AbstractConversionImageHandler (eg createEncodedImage if you want data URIs).

Categories