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

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

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?

File upload with in Spring MVC without adding any additional parameter in controller method

I am using spring boot 2. My new task is file uploading. I already did it. But I am asked to do it without adding a additional parameter to controller method like #RequestParam("files") MultipartFile files[]. I want to get this from request instead of adding this parameter.
How can I solve this?
I am adding my current code following.
#RequestMapping(value="/uploadMultipleFiles", method=RequestMethod.POST)
public #ResponseBody String handleFileUpload( #RequestParam("files") MultipartFile files[]){
try {
String filePath="c:/temp/kk/";
StringBuffer result=new StringBuffer();
byte[] bytes=null;
result.append("Uploading of File(s) ");
for (int i=0;i<files.length;i++) {
if (!files[i].isEmpty()) {
bytes = files[i].getBytes();
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath+files[i].getOriginalFilename())));
stream.write(bytes);
stream.close();
result.append(files[i].getOriginalFilename() + " Ok. ") ;
}
else
result.append( files[i].getOriginalFilename() + " Failed. ");
}
return result.toString();
} catch (Exception e) {
return "Error Occured while uploading files." + " => " + e.getMessage();
}
}
You can get files from HttpRequest:
#RequestMapping(value="/uploadMultipleFiles", method=RequestMethod.POST)
public String handleFileUpload(HttpRequest request){
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> yourFiles = multipartRequest.getFileMap();
return "All is Ok!";
}
My sample code.
#RequestMapping(value = "/multiple/upload", method = RequestMethod.POST)
public #ResponseBody String test(#RequestParam(value = "files[]") List<MultipartFile> files,
HttpServletRequest req) {
MultipartFileWriter writer = new MultipartFileWriter();
String folderPath = "/file/";
for (MultipartFile file : files) {
writer.writeFile(file, folderPath, req);
}
return "success";
}

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 ??

Spring error: IllegalStateException: Cannot call sendRedirect() after the response has been committed and getOutputStream() has already been called

I have got an error when I try to download a zipped file using Spring boot and spring MVC:
Errors:
SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed] with root cause
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
SEVERE: Servlet.service() for servlet dispatcherServlet threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
Basically, my app is loading a file, zipping it and download the new zip file.
This is my application Controller:
#Controller
public class ApplicationController {
public String fileZipped;
public String inputFile;
#RequestMapping(method = RequestMethod.GET, value = "/uploadForm")
public String provideUploadInfo() {
return "uploadForm";
}
#RequestMapping(method = RequestMethod.POST, value = "/")
public String handleFileUpload(#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes,
HttpServletResponse downloadResponse) {
if (!file.isEmpty()) {
try {
inputFile = file.getOriginalFilename();
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(new File(Application.UPLOAD_DIR + "/" + inputFile)));
FileCopyUtils.copy(file.getInputStream(), stream);
stream.close();
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
FileUtils.copyDirectory(Application.UPLOAD_DIR, Application.OUTPUT_FOLDER);
FileUtils.cleanDirectory(new File(Application.UPLOAD_DIR));
}
catch (Exception e) {
redirectAttributes.addFlashAttribute("message",
"You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage());
}
}
else {
redirectAttributes.addFlashAttribute("message",
"You failed to upload " + file.getOriginalFilename() + " because the file was empty");
}
return "redirect:/zipFiles";
}
#RequestMapping(value = "/download")
public String handleFileDownload(HttpServletResponse downloadResponse) throws IOException {
InputStream inputStream = null;
OutputStream outStream = null;
try {
if ( fileZipped!=null && Files.exists(Paths.get(fileZipped))) {
inputStream = new FileInputStream(fileZipped);
downloadResponse.setContentType(fileZipped);
downloadResponse.addHeader("Content-Disposition", "attachment; filename=" + Paths.get(fileZipped).getFileName().toString());
outStream = downloadResponse.getOutputStream();
org.apache.commons.io.IOUtils.copy(inputStream, outStream);
downloadResponse.flushBuffer();
}
} catch (IOException e) {
throw new RuntimeException("IOError writing file to output stream");
} finally {
if (inputStream != null) inputStream.close();
if (outStream != null) outStream.close();
}
return "redirect:/uploadForm";
}
#RequestMapping(value="/zipFiles")
public String handleFileZip() throws IOException {
if(inputFile!=null) {
fileZipped = zipFiles(Application.OUTPUT_FOLDER, inputFile);
}
return "redirect:/download";
}
private String zipFiles(String folder, String zipFileName) throws IOException {
String zipFile = folder + "/" + FilenameUtils.removeExtension(zipFileName) + ".zip";
FileOutputStream fileOutputstream = new FileOutputStream(zipFile);
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputstream));
File []filesArray = new File(folder).listFiles();
for (File file : filesArray){
if (!FilenameUtils.getExtension(file.getAbsolutePath()).equals("zip")) {
byte[] buffer = new byte[1024];
FileInputStream fileInputStream = new FileInputStream(file);
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
int length;
while ((length = fileInputStream.read()) > 0) {
zipOutputStream.write(buffer, 0, length);
}
zipOutputStream.closeEntry();
fileInputStream.close();
}
}
zipOutputStream.close();
return zipFile;
}
I do no know why that is happening if I am closing the input and output streams.
Thanks you very much for your help.
The problem is with the redirect. Instead of
return "redirect:/uploadForm";
return the view name.
return "/uploadForm";

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