Created
September 4, 2024 09:12
-
-
Save spmasterman/dc3f5e79438d70258c5702e22c78484d to your computer and use it in GitHub Desktop.
multipart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Shaun Masterman ([email protected]) | |
*/ | |
@Path("/inbound") | |
@Component | |
public class Inbound { | |
protected final Logger logger = LoggerFactory.getLogger(Inbound.class); | |
private static String UPLOAD_DIR = "/"; | |
private final ObjectMapper objectMapper; | |
@Inject | |
public Inbound(final ObjectMapper objectMapper) { | |
this.objectMapper = objectMapper; | |
} | |
@POST | |
@Path("/") | |
@Consumes(MediaType.MULTIPART_FORM_DATA_VALUE) | |
@Produces(MediaType.TEXT_PLAIN_VALUE) | |
public Response handleFileUploadForm(@MultipartForm MultipartFormDataInput input) throws IOException { | |
Map<String, List<InputPart>> uploadForm = input.getFormDataMap(); | |
List<String> fileNames = new ArrayList<>(); | |
List<InputPart> inputParts = uploadForm.get("attachment-info"); | |
System.out.println("inputParts size: " + inputParts.size()); | |
Map<String, Object> attachments = objectMapper.readValue(inputParts.get(0).getBody(InputStream.class, null), new TypeReference<>(){}); | |
logger.info("map : {}", String.join(", ", attachments.keySet())); | |
for (String attachmentName : attachments.keySet()) { | |
for (InputPart inputPart : uploadForm.get(attachmentName)) { | |
String fileName = null; | |
try { | |
MultivaluedMap<String, String> header = inputPart.getHeaders(); | |
fileName = getFileName(header); | |
fileNames.add(fileName); | |
System.out.println("File Name: " + fileName); | |
InputStream inputStream = inputPart.getBody(InputStream.class, null); | |
byte[] bytes = IOUtils.toByteArray(inputStream); | |
// | |
File customDir = new File(UPLOAD_DIR); | |
fileName = customDir.getAbsolutePath() + File.separator + fileName; | |
Files.write(Paths.get(fileName), bytes, StandardOpenOption.CREATE_NEW); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
String uploadedFileNames = String.join(", ", fileNames); | |
return Response.ok().entity("All files " + uploadedFileNames + " successfully.").build(); | |
} | |
private String getFileName(MultivaluedMap<String, String> header) { | |
String[] contentDisposition = header.getFirst("Content-Disposition").split(";"); | |
for (String filename : contentDisposition) { | |
if ((filename.trim().startsWith("filename"))) { | |
String[] name = filename.split("="); | |
String finalFileName = name[1].trim().replaceAll("\"", ""); | |
return finalFileName; | |
} | |
} | |
return "unknown"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment