This is my code, I am here accept excell file and read it .After than I read of excell file of row values and insert them to database,which to the appropriate columns. At the end, I put the file in the folder that I have determined on the computer. But I am having a problem here,When I want to download the file with the same name a few times in the api, it shows that I only uploaded first time it to the folder at first,but it prints the values to the database. I can't make any logic about it, what do you think I can do here?
@Override
public ResponseEntity<? extends Response> acceptExcelFileAndSenderName(MultipartFile filePath, String senderName) throws IOException {
String fileName = filePath.getOriginalFilename();
if (fileName.substring(fileName.length() - 5).equals(".xlsx")) {
try (InputStream excelFile = filePath.getInputStream()) {
String phoneNumber = "";
String textMessage = "";
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
if (currentCell.getCellType() == CellType.NUMERIC) {
phoneNumber = NumberToTextConverter.toText(currentCell.getNumericCellValue());
} else if (currentCell.getCellType() == CellType.STRING) {
textMessage = String.valueOf(currentCell.getStringCellValue());
}
}
FileDetail fileDetail = new FileDetail();
fileDetail.setPhoneNumber(phoneNumber);
fileDetail.setTextMessage(textMessage);
fileDetail.setSender(senderName);
this.fileDetailRepository.save(fileDetail);
}
excelFile.close();
String destination = "C:\\Users\\anar.memmedov\\Desktop\\app\\" filePath.getOriginalFilename();
File file1 = new File(destination);
filePath.transferTo(file1);
return new ResponseEntity<>(new SuccessResponse(MessageCase.FILE_SUCCESSFULLY_WRITTEN_TO_DATABASE.getMessage(), 200), HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
}
}
return new ResponseEntity<>(new ErrorResponse(MessageCase.FAILED_HAPPEND_WHEN_FILE_WRITTEN_TO_DATABASE.getMessage(), 400), HttpStatus.BAD_REQUEST);
}
CodePudding user response:
try creating a unique file name for every file, eg:
String destination = "C:\\Users\\anar.memmedov\\Desktop\\app\\" System.nanoTime() "_" filePath.getOriginalFilename();
CodePudding user response:
I changed some things and worked, and it looks like this
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
String destination = "C:\\Users\\anar.memmedov\\Desktop\\app\\" "_" LocalDateTime.now().format(dateTimeFormatter) "_" filePath.getOriginalFilename();