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 ??
Related
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?
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
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
Shall I remove this from application.properties
spring.http.multipart.enabled=true
What should be my approach towards this file upload without using multipart?
This way, I'm able to uploading file using where I'm using multipart.
#RequestMapping(value = "/dog/create/{name}", method = RequestMethod.POST)
public JsonNode dogCreation(HttpServletRequest httpRequest, #RequestParam(value = "picture", required = false) MultipartFile multipartFile,
#PathVariable("name") String name) throws IOException, InterruptedException {
JSONObject response = new JSONObject();
Dog dog = new Dog();
String DOG_IMAGES_BASE_LOCATION = "resource\\images\\dogImages";
try {
File file = new File(DOG_IMAGES_BASE_LOCATION);
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
dog = dogService.getDogByName(name);
if (dog == null) {
if (!multipartFile.isEmpty()) {
String multipartFileName = multipartFile.getOriginalFilename();
String format = multipartFileName.substring(multipartFileName.lastIndexOf("."));
try {
Path path = Paths.get(DOG_IMAGES_BASE_LOCATION + "/" + name + format);
byte[] bytes = multipartFile.getBytes();
File file = new File(path.toString());
file.createNewFile();
Files.write(path, bytes);
if (file.length() == 0) {
response = utility.createResponse(500, Keyword.ERROR, "Image upload failed");
} else {
String dbPath = path.toString().replace('\\', '/');
dog = new Dog();
dog.setName(name);
dog.setPicture(dbPath);
dog = dogService.dogCreation(dog);
response = utility.createResponse(200, Keyword.SUCCESS, "Image upload successful");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return objectMapper.readTree(response.toString());
}
I want to do it without using multipart, what would you suggest?
This is what I've done till now to solve this
#RequestMapping(value = "/dog/create/{name}", method = RequestMethod.POST)
public JsonNode dogCreation(HttpServletRequest httpRequest, #RequestParam("picture") String picture,
#PathVariable("name") String name) throws IOException, InterruptedException {
JSONObject response = new JSONObject();
Dog dog = new Dog();
String DOG_IMAGES_BASE_LOCATION = "resource\\images\\dogImages";
try {
File file = new File(DOG_IMAGES_BASE_LOCATION);
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
dog = dogService.getDogByName(name);
if (dog == null) {
if (!picture.isEmpty()) {
String dogPicture = picture;
byte[] encodedDogPicture = Base64.encodeBase64(dogPicture.getBytes());
String format = dogPicture.substring(picture.lastIndexOf("."));
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
return objectMapper.readTree(response.toString());
}
I just have to say that this should probably only be used as a workaround.
On your frontend, convert the file to base64 in js:
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(evt) {
console.log(evt.target.result);
//do POST here - something like this:
$.ajax("/upload64", {
method: "POST",
contentType: "application/text"
data: evt.target.result
}
};
On the server with an example of a decoder - more decoding options here Decode Base64 data in Java
import sun.misc.BASE64Decoder;
#PostMapping("/upload64")
public String uploadBase64(#RequestBody String payload){
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
//use your bytes
}
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";
}