简体   繁体   中英

Is there any way to filter request (multipart/form-data) by content-type of attached file?

I'm developing web backend on Java, that allows upload files with "multipart/form-data" content-type and attached file. For API part I use JAX-RS. I want use different API methods for different content-types of attached files. For example, for "application/pdf" I want use uploadDocument method, and for "application/json" uploadData method.

@POST
@Consumes("multipart/form-data")
void uploadDocument(@Multipart("file") File file);

@POST
@Consumes("multipart/form-data")
void uploadData(@Multipart("file") File file);

So, can I filter requests, based on attached file content-type?

PS if you didn't understand, please describe what, I will explain more.

Only This is just getting idea to implement

  • You can use java 8 stream APi to do it simply
@PostMapping(
      value = "/uploadDocuments",
      consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
  public void uploadDocument(
      @RequestParam(required = true) MultipartFile[] file,) {

    try {

      Arrays.asList(files).stream()
          .filter(
              x ->
                  FilenameUtils.getExtension(x.getOriginalFilename()).equals("pdf")
                      || FilenameUtils.getExtension(x.getOriginalFilename()).equals("txt"))
          .forEach(
              x -> {
                try (BufferedReader reader =
                    new BufferedReader(
                        new InputStreamReader(
                            new ByteArrayInputStream(x.getBytes()),
                            "UTF-8"))) {
                  Supplier<Stream<String>> fileContentStream = reader::lines;
                  if (FilenameUtils.getExtension(x.getOriginalFilename()).equals("pdf")) {

                    String[] fileReadLines =
                        fileContentStream
                            .get()
                            .skip(1)// you can skip any line with this action
                            .map(firstLine -> firstLine.split(","))// you can use this seperate your line if you want to split
                            .findFirst()
                            .orElse(null);



                            }
                            else if (FilenameUtils.getExtension(x.getOriginalFilename()).equals("csv")) {

//Like above , I have added , you can do here for various file format 

 } catch (Exception ex) {

}

                            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM