How to divide large csv file into multiple csv files using chunk size - spring

How to write spring batch configuration class for single csv into multiple csv files ,it should divide based on chunk size and it should divide into multiple csv file based on chunk capacity
How to write spring batch configuration class for single csv into multiple csv files ,it should divide based on chunk size and it should divide into multiple csv file based on chunk capacity
package com.codenotfound.batch;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.builder.FlatFileItemWriterBuilder;
import org.springframework.batch.item.file.transform.PassThroughLineAggregator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import com.codenotfound.model.Person;
#Configuration
public class HelloWorldJobConfig {
#Bean
public Job helloWorlJob(JobBuilderFactory jobBuilders,
StepBuilderFactory stepBuilders) {
return jobBuilders.get("helloWorldJob")
.start(helloWorldStep(stepBuilders)).build();
}
#Bean
public Step helloWorldStep(StepBuilderFactory stepBuilders) {
return stepBuilders.get("helloWorldStep")
.<Person, String>chunk(10).reader(reader())
.processor(processor()).writer(writer()).build();
}
#Bean
public FlatFileItemReader<Person> reader() {
return new FlatFileItemReaderBuilder<Person>()
.name("personItemReader")
.resource(new ClassPathResource("csv/persons.csv"))
.delimited().names(new String[] {"firstName", "lastName"})
.targetType(Person.class).build();
}
#Bean
public PersonItemProcessor processor() {
return new PersonItemProcessor();
}
#Bean
public FlatFileItemWriter<String> writer() {
return new FlatFileItemWriterBuilder<String>()
.name("greetingItemWriter")
.resource(new FileSystemResource(
"target/test-outputs/greetings.txt"))
.lineAggregator(new PassThroughLineAggregator<>()).build();
}
}
t

Related

SFTP File Download in Spring Boot

I created one spring boot app. I need to upload any file(doc,pdf,mp3 etc..) on sftp server. when user upload file my spring app can able to create url and save file details(on which server file is located, download url of file, who is the own of that file etc..) to h2 database.
and when user ask for file.. spring boot can able to fetch file details form database.. and display that file on browser. and user can also able to download that file. can any one help..enter image description here
Java Configuration
import com.example.springintegrationhttp.FilePrinter;
import org.springframework.context.annotation.Bean;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.file.FileNameGenerator;
import org.springframework.integration.file.filters.AcceptOnceFileListFilter;
import org.springframework.integration.sftp.filters.SftpSimplePatternFileListFilter;
import org.springframework.integration.sftp.inbound.SftpInboundFileSynchronizer;
import org.springframework.integration.sftp.inbound.SftpInboundFileSynchronizingMessageSource;
import org.springframework.integration.sftp.outbound.SftpMessageHandler;
import org.springframework.integration.sftp.session.DefaultSftpSessionFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Component;
import java.io.File;
#org.springframework.context.annotation.Configuration
#Component
public class Configuration {
#Bean
public DefaultSftpSessionFactory sftpSessionFactory(){
DefaultSftpSessionFactory defaultSftpSessionFactory = new DefaultSftpSessionFactory();
defaultSftpSessionFactory.setHost("0.0.0.0");
defaultSftpSessionFactory.setPort(22);
defaultSftpSessionFactory.setUser("abhishek");
defaultSftpSessionFactory.setPassword("12345");
defaultSftpSessionFactory.setAllowUnknownKeys(true);
System.out.println("Value in SftpSession: " + defaultSftpSessionFactory);
return defaultSftpSessionFactory;
}
#Bean
#ServiceActivator(inputChannel = "tosftpChannel")
public MessageHandler handler(){
SftpMessageHandler messageHandler = new SftpMessageHandler(sftpSessionFactory());
messageHandler.setRemoteDirectoryExpression(new LiteralExpression("upload"));
messageHandler.setFileNameGenerator(new FileNameGenerator() {
#Override
public String generateFileName(Message<?> message) {
System.out.println(message.getHeaders().get("fileName"));
System.out.println(message.getPayload());
return message.getHeaders().get("fileName").toString();
}
});
return messageHandler;
}
#Bean
public SftpInboundFileSynchronizer sftpInboundFileSynchronizer(){
SftpInboundFileSynchronizer fileSynchronizer = new SftpInboundFileSynchronizer(sftpSessionFactory());
fileSynchronizer.setDeleteRemoteFiles(false);
fileSynchronizer.setRemoteDirectory("upload");
System.out.println("M a gaya");
fileSynchronizer.setFilter(new SftpSimplePatternFileListFilter("*.txt"));
return fileSynchronizer;
}
#Bean
//#InboundChannelAdapter(channel = "sftpChannel", poller = #Poller(fixedDelay = "5000"))//,autoStartup = "false")
#InboundChannelAdapter(channel = "sftpChannel")//,autoStartup = "false")
public MessageSource<File> sftpMessageSource(){
System.out.println("Into sftpMessageSource()");
SftpInboundFileSynchronizingMessageSource source = new SftpInboundFileSynchronizingMessageSource(sftpInboundFileSynchronizer());
source.setLocalDirectory(new File("target/foo"));
source.setAutoCreateLocalDirectory(true);
System.out.println("Flow");
source.setLocalFilter(new AcceptOnceFileListFilter<File>());
source.setMaxFetchSize(1);
//sftpInboundFileSynchronizer();
return source;
}
/*OutBoundGateway*/
/* #Bean
#ServiceActivator(inputChannel = "sftpChannel",)
public MessageHandler handler(){
SftpOutboundGateway outboundGateway = new SftpOutboundGateway(sftpSessionFactory(),
"get","payload");
outboundGateway.setLocalDirectory(new File("target/gatewayhand"));
outboundGateway.setAutoCreateLocalDirectory(true);
return outboundGateway;
}*/
/*OutBoundGateway*/
#Bean
#ServiceActivator(inputChannel = "sftpChannel")
public MessageHandler DownloadHandler(){
//return new SftpOutboundGateway(sftpSessionFactory(),"ls");
return message -> {
System.out.println("In Service Activator: " + message.getPayload());
File f = (File) message.getPayload();
FilePrinter f2 = new FilePrinter();
f2.print(f);
System.out.println(f.getName());
//sftpMessageSource();
//p.print(File file);
};
}
}
Gateway
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.InputStream;
#Component
#MessagingGateway
public interface UplaodGateway {
#Gateway(requestChannel = "tosftpChannel")
public void sendToSftp(#Header("fileName") String fileName, InputStream file);
/* #Gateway(requestChannel = "sftpChannel")
public void read(String fileName);*/
}
Controller
import com.example.springintegrationhttp.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.websocket.server.PathParam;
import java.io.IOException;
#RestController
//#RequiredArgsConstructor
public class uplaodController {
#Autowired
UploadService uploadService;
#PostMapping("/upload")
public ResponseEntity<String> upladFile(#RequestParam("file")MultipartFile file) throws IOException {
return uploadService.uplaodToServer(file);
}
#GetMapping("/read")
public String readf(#PathParam("fileName")String fileName){
uploadService.readFileFromServer(fileName);
return "I want to fetch that file which user want";
}
}
//}
Thank You

Scaling Spring Batch using AsyncItemProcessor and AsyncItemWriter

I am trying to write a solution to scale a spring batch. In the spring batch it's reading data (600 000) from the MySQL database and then process it and update the status of each processed row as 'Completed'.
I am using AsyncItemProcessor and AsyncItemWriter for scaling the spring batch.
Problem:
If I run the spring batch synchronously then it's taking same or less time while running the spring batch asynchronously. I am not getting the benefit of using multi threading.
package com.example.batchprocessing;
import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.integration.async.AsyncItemProcessor;
import org.springframework.batch.integration.async.AsyncItemWriter;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor;
import org.springframework.batch.item.file.transform.DelimitedLineAggregator;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.support.CompositeItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.core.task.TaskExecutor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
#Configuration
#EnableBatchProcessing
public class BatchConfiguration {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Bean
public JdbcCursorItemReader<Person> reader(DataSource dataSource) {
JdbcCursorItemReader<Person> reader = new JdbcCursorItemReader<>();
reader.setDataSource(dataSource);
reader.setSql("SELECT * from people");
reader.setRowMapper(new UserRowMapper());
return reader;
}
#Bean
public PersonItemProcessor processor() {
return new PersonItemProcessor();
}
#Bean
public AsyncItemProcessor<Person, Person> asyncItemProcessor() throws Exception {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(30);
executor.setMaxPoolSize(50);
executor.setQueueCapacity(10000);
executor.setThreadNamePrefix("BatchProcessing-");
executor.afterPropertiesSet();
AsyncItemProcessor<Person, Person> asyncProcessor = new AsyncItemProcessor<>();
asyncProcessor.setDelegate(processor());
asyncProcessor.setTaskExecutor(executor);
asyncProcessor.afterPropertiesSet();
return asyncProcessor;
}
#Bean
public JdbcBatchItemWriter<Person> writer(DataSource dataSource) {
return new JdbcBatchItemWriterBuilder<Person>()
.itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
.sql("UPDATE people set status= 'completed' where person_id= :id")
.dataSource(dataSource)
.build();
}
#Bean
public AsyncItemWriter<Person> asyncItemWriter() {
AsyncItemWriter<Person> asyncWriter = new AsyncItemWriter<>();
asyncWriter.setDelegate(writer(null));
return asyncWriter;
}
#Bean
public Job importUserJob(JobCompletionNotificationListener listener, Step step1) {
return jobBuilderFactory.get("importUserJob")
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(step1)
.end()
.build();
}
#Bean
public Step step1(JdbcBatchItemWriter<Person> writer) throws Exception {
return stepBuilderFactory.get("step1")
.<Person, Person> chunk(10000)
.reader(reader(null))
//.processor(processor())
//.writer(writer)
.processor((ItemProcessor) asyncItemProcessor())
.writer(asyncItemWriter())
//.throttleLimit(30)
.build();
}
}
What am I doing wrong? Why is the AsyncItemProcessor taking more/same time as synchronous processing? Usually it should take less time. I can see in the log multiple thread is working but eventually the end time is the same as synchronous processing.
I agree to #5019386, asyncItemProcessor is helpful when processing an item is expensive. One suggestion that I can make is to move the code to create ThreadPoolTaskExecutor into a separate block as a bean so that you can avoid creating threads.

Implementing JUnit test cases in Spring batch Jobs calling from Controller

I am new to Junit. I am literally struggling to write Junit test cases for my code. I am working with Spring boot, Batch and JPA. I configured Jobs,file read and write in to DB everything working fine. But when it comes to JUnit, I don't even get an idea to write code. Can anyone help me. Below is my code
FileProcessController.java
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.sc.batchservice.model.StatusResponse;
import lombok.extern.slf4j.Slf4j;
#Slf4j
#RestController
#RequestMapping("/fileProcess")
public class FileProcessController {
#Autowired
private JobLauncher jobLauncher;
#Autowired
#Qualifier("euronetFileParseJob")
private Job job;
#GetMapping(path = "/process")
public #ResponseBody StatusResponse process() throws Exception {
try {
Map<String, JobParameter> parameters = new HashMap<>();
parameters.put("date", new JobParameter(new Date()));
jobLauncher.run(job, new JobParameters(parameters));
return new StatusResponse(true);
} catch (Exception e) {
log.error("Exception", e);
Throwable rootException = ExceptionUtils.getRootCause(e);
String errMessage = rootException.getMessage();
log.info("Root cause is instance of JobInstanceAlreadyCompleteException --> "+(rootException instanceof JobInstanceAlreadyCompleteException));
if(rootException instanceof JobInstanceAlreadyCompleteException){
log.info(errMessage);
return new StatusResponse(false, "This job has been completed already!");
} else{
throw e;
}
}
}
}
BatchConfig.java
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import com.sc.batchservice.model.DetailsDTO;
#Configuration
#EnableBatchProcessing
public class BatchConfig {
private JobBuilderFactory jobBuilderFactory;
#Autowired
public void setJobBuilderFactory(JobBuilderFactory jobBuilderFactory) {
this.jobBuilderFactory = jobBuilderFactory;
}
#Autowired
StepBuilderFactory stepBuilderFactory;
#Value("file:${input.files.location}${input.file.pattern}")
private Resource[] fileInputs;
#Value("${euronet.file.column.names}")
private String filecolumnNames;
#Value("${euronet.file.column.lengths}")
private String fileColumnLengths;
#Value("${input.files.location}")
private String inputFileLocation;
#Value("${input.file.pattern}")
private String inputFilePattern;
#Autowired
FlatFileWriter flatFileWriter;
#Bean
public Job euronetFileParseJob() {
return jobBuilderFactory.get("euronetFileParseJob")
.incrementer(new RunIdIncrementer())
.start(fileStep())
.build();
}
public Step fileStep() {
return stepBuilderFactory.get("fileStep")
.<DetailsDTO, DetailsDTO>chunk(10)
.reader(new FlatFileReader(fileInputs, filecolumnNames, fileColumnLengths))
.writer(flatFileWriter)
.build();
}
}
FlatFileReader.java
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.MultiResourceItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FixedLengthTokenizer;
import org.springframework.core.io.Resource;
import com.sc.batchservice.model.DetailsDTO;
import com.sc.batchservice.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
#Slf4j
public class FlatFileReader extends MultiResourceItemReader<DetailsDTO> {
public EuronetFlatFileReader(Resource[] fileInputs, String filecolumnNames, String fileColumnLengths) {
setResources(fileInputs);
setDelegate(reader(filecolumnNames, fileColumnLengths));
setStrict(true);
}
private FlatFileItemReader<DetailsDTO> reader(String filecolumnNames, String fileColumnLengths) {
FlatFileItemReader<DetailsDTO> flatFileItemReader = new FlatFileItemReader<>();
FixedLengthTokenizer tokenizer = CommonUtil.fixedLengthTokenizer(filecolumnNames, fileColumnLengths);
FieldSetMapper<DetailsDTO> mapper = createMapper();
DefaultLineMapper<DetailsDTO> lineMapper = new DefaultLineMapper<>();
lineMapper.setLineTokenizer(tokenizer);
lineMapper.setFieldSetMapper(mapper);
flatFileItemReader.setLineMapper(lineMapper);
return flatFileItemReader;
}
/*
* Mapping column data to DTO
*/
private FieldSetMapper<DetailsDTO> createMapper() {
BeanWrapperFieldSetMapper<DetailsDTO> mapper = new BeanWrapperFieldSetMapper<>();
try {
mapper.setTargetType(DetailsDTO.class);
} catch(Exception e) {
log.error("Exception in mapping column data to dto ", e);
}
return mapper;
}
}
I have Writer,Entity and model classes also, But if any example or idea upto this code, I can proceed with those classes.

how to create two data source in springboot where secondary database is dependent upon the primary database (Initially secondary database is unknown)

I want to create an application with two db connection where secondary db connection is selected on the basis of primary.
I have created two datasource one as #primary and secondary i created after the home page loaded but wasn't working
i have done something like this but not able to create second one
package com.example.edunext.Configuration;
import com.example.edunext.model.User;
import com.example.edunext.model.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.DependsOn;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
#Component
public class Registry {
private static final Map<String, Object> registry = new HashMap<String, Object>();
#Autowired
#Qualifier("jdbcTemplate1")
private JdbcTemplate jdbcTemplate1;
public String getdb()
{
String sql1 = "select email from user1";
List<User> list1 = jdbcTemplate1.query(sql1, new UserDaoImpl.UserRowMapper());
return list1.get(0).getEmail();
}
#Bean(name = "db2")
#DependsOn("db1")
#ConfigurationProperties(prefix = "spring.second-db")
public DataSource dataSource2() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
try {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
String jdbcurl="jdbc:mysql://localhost:3306/"+getdb();
dataSource.setUrl(jdbcurl);
dataSource.setUsername("root");
dataSource.setPassword("hrhk");
return dataSource;
}
catch(Exception ex)
{
return dataSource;
}
}
#Bean(name = "jdbcTemplate2")
#DependsOn("jdbcTemplate1")
public JdbcTemplate jdbcTemplate2(#Qualifier("db2") DataSource ds) {
if(ds==null)
{
return null;
}
else {
return new JdbcTemplate(ds);
}
}
}

springboot InputStream

I have a controller
void upload(#RequestParam(value="file", MultiPartFile file, #RequestParam(value = "content", required = false) InputStream stream){}
I never get a handle to InputStream when user uploads a file through Stream.
How do i configure that?
The normal file upload works just fine.
I am sending Bzip2 content to upload and multipart default enabled in springboot.
I do get this error.
Caused by: java.lang.IllegalArgumentException: Could not retrieve
InputStream for class path resource [BZh91AY&SY90WT�A�%L
!���!��9D�����ܑN�$�L��]:
at
org.springframework.beans.propertyeditors.InputStreamEditor.setAsText(InputStreamEditor.java:77)
at
org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:449)
at
org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:422)
at
org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:195)
at
org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:107)
at
org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:64)
Controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.flasher.service.ImageService;
#RestController
public class ImageControllerRest {
#Autowired
ImageService imageService;
#PostMapping("/upload_img")
public ResponseEntity<?> uploadImage(#RequestParam("file") MultipartFile file, Authentication authentication) {
try {
imageService.store(file, authentication.getName());
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
Service
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.flasher.util.UUIDGenerator;
#Service
public class ImageService {
#Value("${flasher.absolute.img.path}")
String imageUploadPath;
#Autowired
UUIDGenerator uuidGenerator;
public void store(MultipartFile file, String username) {
try {
File uploadFolder = new File(imageUploadPath+username);
if (!uploadFolder.exists()) {
uploadFolder.mkdirs();
}
Files.copy(file.getInputStream(),
Paths.get(uploadFolder.getAbsolutePath()).resolve(uuidGenerator.generateUUID()+"."+file.getContentType().split("/")[1]));
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can achive file upload by this way

Resources