@Path("files")
@Log4j2
@Component
public class FileUploadController implements ConfigInterface{
@Context
private SecurityContext securityContext;
@Inject
private FileUploadAPIValidator paramValidator;
@Path("/config")
public Resource getConfigResource() {
return Resource.from(ConfigController.class);
}
/**
* @author lokman 20/11/2022
*
*/
@POST
@Secured
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@RequestTracingFilter
public Response uploadMultipleFile(@FormDataParam("files") List<FormDataBodyPart> files, @FormDataParam("files") List<FormDataContentDisposition> fileDetails) {
log.info("file size :"+ fileDetails.size());
JSONObject response = new JSONObject();
BasicCacheUserPrincipal userPrincipal = (BasicCacheUserPrincipal) securityContext.getUserPrincipal();
if (userPrincipal == null || userPrincipal.getUser() == null) {
response.put("responseCode", HttpStatus.SC_UNAUTHORIZED);
response.put("message", "Unauthorized");
response.put("success", Boolean.FALSE);
return Response.status(HttpStatus.SC_UNAUTHORIZED).entity(response.toString()).build();
}
if (fileDetails.size() == 1 && StringUtil.isBlank(fileDetails.get(0).getFileName())) {
response.put("responseCode", HttpStatus.SC_OK);
response.put("message", "No file selected.");
response.put("success", Boolean.FALSE);
return Response.status(HttpStatus.SC_UNAUTHORIZED).entity(response.toString()).build();
}
if (fileDetails.size() > DefaultConfig.MAX_FILE_SIZE) {
response.put("responseCode", HttpStatus.SC_OK);
response.put("message", "Maximum 10 files allowed.");
response.put("success", Boolean.FALSE);
return Response.status(HttpStatus.SC_UNAUTHORIZED).entity(response.toString()).build();
}
List<String> fileUrls = new ArrayList<>();
for (int j = 0; j < files.size(); j++) {
FormDataBodyPart formDataBodyPartFile = files.get(j);
ContentDisposition contentDispositionHeader = formDataBodyPartFile.getContentDisposition();
InputStream fileInputStream = formDataBodyPartFile.getValueAs(InputStream.class);
FormDataContentDisposition fileDetail = (FormDataContentDisposition) contentDispositionHeader;
FileUploadAPIValidationResponse verifyResponse = paramValidator.verifyFiles(fileInputStream, fileDetail);
File tempFile = null;
if(verifyResponse.isValid()) {
String fileName = userPrincipal.getUser().getId() + "_" + "form" + "_" + System.currentTimeMillis() + "_" + fileDetail.getFileName();
log.info("fileName :"+ fileName);
tempFile = new File(fileName);
FileOutputStream fileOutputStream = writeToFile(verifyResponse.getInputStream(), tempFile);
log.debug("file length : "+ tempFile.length());
if ((tempFile.length() / CommonUtils.ONE_MEGABYTE_IN_BYTES) > DefaultConfig.MAX_FILE_SIZE) {
removeExistingFile(tempFile);
fileOutputStream = null;
continue;
}
if (fileOutputStream != null) {
String fileUrl = uploadFileToS3(tempFile);
if (StringUtil.isNotBlank(fileUrl)) {
log.info("fileUrl :" + fileUrl);
fileUrls.add(fileUrl);
}
}
}
if(tempFile != null) {
removeExistingFile(tempFile);
}
}
log.info("fileUrls :"+ fileUrls.size());
if(fileUrls.isEmpty()) {
response.put("responseCode", HttpStatus.SC_OK);
response.put("message", "File upload failed.");
response.put("success", Boolean.FALSE);
return Response.status(HttpStatus.SC_OK).entity(response.toString()).build();
}
response.put("responseCode", HttpStatus.SC_OK);
response.put("message", "File uploaded successfully.");
response.put("success", Boolean.TRUE);
response.put("urls", fileUrls);
return Response.status(HttpStatus.SC_OK).entity(response.toString()).build();
}
/**
* @author lokman 19/11/2022
*
*/
private FileOutputStream writeToFile(InputStream inputStream, File tempFile) {
byte[] data = new byte[1024];
FileOutputStream fileOutputStream = null;
int read = 0;
try {
fileOutputStream = new FileOutputStream(tempFile);
while ((read = inputStream.read(data)) != -1) {
fileOutputStream.write(data, 0, read);
}
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return fileOutputStream;
}
/**
* @author lokman 19/11/2022
* @param file
*/
private String uploadFileToS3(File file) {
try {
String folder = S3Config.AWS3_SECTION_USER+"/";
log.debug("Folder : "+folder);
AWS3ApiResponse response = AWS3APIFactory.getAWS3API().uploadPublicFile(S3Config.AWS3_BUCKET_NAME, folder, file);
log.info(" s3 upload Success : "+response.isSuccess());
if(response.isSuccess()) {
log.info("FileUrl : "+response.getFileUrl());
return response.getFileUrl();
}
} catch (Exception e) {
log.error("Exception : "+ e);
}
return null;
}
/**
* @author lokman 19/11/2022
* @param file
*/
private void removeExistingFile(File file) {
try {
if (file.exists()) {
boolean fileRemoved = file.delete();
log.debug("fileRemoved : " + fileRemoved);
}
} catch (Exception e) {
log.error("errorMessage ", e);
}
}
}
Monday, December 25, 2023
Upload file to S3 api
Subscribe to:
Post Comments (Atom)
Fluent interface pattern
public class UserConfigurationManager { private String userName; private String password; private UserConfigurationManager() { ...
-
If there is multiple implementation of an interface then we need to specify which one's implementation will use. For that reason we need...
-
public class MainApp { public static void main(String[] args) { String input = "aabbbcccdeefghijkkkkkk"; calculateFrequen...
-
If any event fired on a DOM element it will also fired on all of its parent element which is called the event bubbling. So, the element eve...
No comments:
Post a Comment