使用 Spring Boot 测试端点时出现错误 415“不支持的媒体类型”

问题描述 投票:0回答:1

描述:

我正在使用 Spring Boot 开发 Web 服务,在测试应接收 DTO 列表和文件的端点时遇到问题。当我执行测试时,出现以下错误:

Content-Type 'application/octet-stream' is not supported.
"status": 415,
"error": "Unsupported Media Type"

我已经用 @RequestPart 注释了我的控制器方法以接收 DTO 列表,并配置了 Postman 以将数据作为表单数据发送,但我仍然收到错误。

这是我的控制器方法:

@PostMapping("/upload")
    public  ResponseEntity<?> handleFileUpload(
                                @RequestPart(required = false) List<AtributoDto> atributoDtoList,
                                @RequestPart( value = "file", required = false) MultipartFile file,
                         HttpSession session,
                        @RequestPart(value = "entityId", required = false) Long entityId) {
        log.info("Inicio de handleFileUpload con file: {}", file);
        ResponseEntity<?> response;
        try {
            response = ResponseEntity.ok((atributoService.processAtributos(atributoDtoList,file,session,entityId)));
            log.info("El proceso de carga de archivos se completó con éxito");
        }catch (IOException e){
            log.error("Error en el proceso de carga de archivos: {}", e.getMessage());
            response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error en el proceso de carga de archivos");
        }
        return response;
    }```


service method


@交易 公共字符串 processAtributos(列表 atributoDtoList,MultipartFile 文件,HttpSession 会话,长实体Id) 抛出 IOException { log.info("Inicio del método processAtributos"); 列表ats = new ArrayList<>(); 尝试{

        if (atributoDtoList != null) {
            log.info("Procesando lista de atributos y archivo");

            StringBuilder listaAtributos = new StringBuilder(" ");
            String consultaid = null;
            for (int i = 0; i < atributoDtoList.size(); i++) {
                AtributoDto dto = atributoDtoList.get(i);
                Atributo atributo = new Atributo();
                atributo.setNombreAtributo(dto.nombreAtributo());
                atributo.setDescripcion(dto.descripcion());
                atributo.setXxcntIdTipoDatoFk(dto.xxcntIdTipoDatoFk());
                atributo.setLongitud(dto.longitud());
                atributo.setEsAuditable(dto.esAuditable());
                atributo.setMascara(dto.mascara());
                atributo.setDueno(dto.dueno());
                atributo.setProcesoNace(dto.procesoNace());
                atributo.setEsRequeridoEnFuente(dto.esRequeridoEnFuente());
                atributo.setXxcntIdConsultaFk(dto.xxcntIdConsultaFk());
                atributo.setNombreConsulta(dto.nombreConsulta());
                atributo.setIncluirModificar(dto.modificadoPor());
                if (i == 0) {
                    atributo.setEsLlavePrimaria('1');
                    listaAtributos = new StringBuilder("'" + atributo.getNombreConsulta() + "'");
                    consultaid = String.valueOf(atributo.getXxcntIdConsultaFk());
                } else {
                    atributo.setEsLlavePrimaria('0');
                    listaAtributos.append(",'").append(atributo.getNombreConsulta()).append("'");
                }
                atributo.setEstatus('1');

                /**
                 * Si el objeto JSON tiene una propiedad "found" que es igual a "1", el código interpreta esto como una señal de que el atributo ya existe y necesita ser modificado.
                 * En este caso, busca el atributo existente en la base de datos usando su ID, actualiza sus propiedades, y luego guarda los cambios en la base de datos.
                 * */
                if ("1".equals(dto.found())) { // si el atributo ya existe
                    atributo.setUsuarioModificacion("UsuarioCNT");
                    Long idmodificar = dto.xxcntIdAtributoPk();
                    atributo.setXxcntIdAtributoPk(idmodificar);
                    Date date = new Date();
                    atributo.setFechaModificacion(date);
                    Atributo atrimodificar = getAtributoById(idmodificar);
                    atributo.setFechaCreacion(atrimodificar.getFechaCreacion());
                    atributo.setUsuarioCreacion(atrimodificar.getUsuarioCreacion());
                } else {
                    atributo.setUsuarioCreacion("UsuarioCNT");
                    Date date = new Date();
                    atributo.setFechaCreacion(date);
                }
                Atributo at = createNewAtributte(atributo);
                ats.add(at);
            }
            updateDeleteAtributos(consultaid, listaAtributos.toString());
            consultaDominioService.activarConsulta(consultaid);
            log.info("Lista de atributos procesada");
        } else {
            log.info("No se recibió lista de atributos");
        }


        if (file != null) {
            log.info("Archivo recibido, iniciando procesamiento");
            FileContentHolderDTO fileContentHolderDTO = getFileContentHolderDTO(file);
            List<String> fRow = fileContentHolderDTO.getFRow();
            // escribir el archivo en el disco
            byte[] bytes = file.getBytes();
            Path path = Paths.get(fileContentHolderDTO.getDestination() + file.getOriginalFilename()); // concatena el nombre del archivo con la ruta
            Files.write(path, bytes);

            Entidad e = entidadService.findById(entityId); // obtiene la entidad por ID desde el front es xxcntIdEntidadPk de la clase Entidad
            List<EntidadAtributoPadre> eapToPersist = new ArrayList();
            int i = 0;
            var entidadValorPadre = "";
            List<Long> idsConsultas = new ArrayList();
            //idsConsultas.add(((Atributo) ats.get(0)).getXxcntIdConsultaFk());
            idsConsultas.add(ats.get(0).getXxcntIdConsultaFk());
            List<Long> attrIdSet = getIdAttributeByQueryIdSet(idsConsultas);
            List<ValorAtributo> queriesVa = valorAtributoService.findValorAtributoByIdAttSet(attrIdSet);
            Long firstAttOfFirstQueryOfFirstDomain = -1L;
            for (Atributo a : ats) {
                if (isFirstAttributeOfFirstQueryOfFirstDomain(a.getXxcntIdAtributoPk())) {
                    firstAttOfFirstQueryOfFirstDomain = a.getXxcntIdAtributoPk();
                    break;
                }
            }
            for (String row : fRow) {
                if (i == 0) {
                    i++;
                } else {
                    for (int index = 0; index < row.split(":::").length; index++) {
                        Atributo currentAtt = ats.get(index);
                        Object[] existsValnDb = valorAtributoService.existsValueInMemory(row.split(":::")[index], currentAtt.getXxcntIdAtributoPk(), queriesVa);

                        ValorAtributo valnDB = null;

                        String vaInDBAuxS = "";
                        if ((Boolean) existsValnDb[0]) {
                            valnDB = queriesVa.get((Integer) existsValnDb[1]);
                            vaInDBAuxS = valnDB.getValorAtributo() != null ? valnDB.getValorAtributo() : "";
                        }
                        String col = row.split(":::")[index];
                        if (!(Boolean) existsValnDb[0]) {
                            ValorAtributo va = new ValorAtributo();
                            va.setEntidadAtributo(row.split(":::")[0]);
                            va.setFechaCreacion(new Date());
                            va.setFechaModificacion(new Date());
                            va.setUsuarioCreacion("UsuarioCNT");
                            va.setUsuarioModificacion("UsuarioCNT");
                            va.setValorAtributo(col);
                            if (currentAtt.getXxcntIdTipoDatoFk() == 1L) {
                                try {
                                    va.setValorAtributoNumero(BigDecimal.valueOf(Double.parseDouble(col)));
                                } catch (NumberFormatException nfe) {
                                    va.setValorAtributoNumero(null);
                                }
                            } else if (currentAtt.getXxcntIdTipoDatoFk() == 3L) {
                                try {
                                    va.setValorAtributoFecha(new SimpleDateFormat("dd/MM/yyyy").parse(col));
                                } catch (ParseException ex) {
                                    Logger.getLogger(AtributoController.class.getName()).log(Level.SEVERE, null, ex);
                                } finally {
                                    va.setValorAtributoFecha(null);
                                }
                            }
                            boolean isFirst = currentAtt.getXxcntIdAtributoPk().longValue() == firstAttOfFirstQueryOfFirstDomain.longValue();
                            if (isFirst) {
                                long consultaFK = currentAtt.getXxcntIdConsultaFk();
                                long me = e.getXxcntIdEntidadPk();
                                Long parent = e.getEntidadPadre();
                                long fParent = parent == 0L ? me : parent;

                                entidadAtributoPadreService.cleanByIdParentIdAndEntityValue(me, fParent, col);
                                boolean hasParent = (e.getEntidadPadre() != null) && (e.getEntidadPadre() != 0L);
                                int[] parentIndexes = indexesOfParentAndUserValues(consultaFK, hasParent, ats);
                                EntidadAtributoPadre eap = new EntidadAtributoPadre();
                                eap.setEntidadId(me);
                                eap.setEntidadPadreId(fParent);
                                try {
                                    eap.setValorEntidadPadre(row.split(":::")[parentIndexes[0]]);
                                } catch (NullPointerException npe) {
                                    eap.setValorEntidadPadre(col);
                                }
                                eap.setValorEntidad(col);
                                Object pv = null;
                                try {
                                    pv = row.split(":::")[parentIndexes[1]];
                                } catch (NullPointerException npe) {
                                }
                                String s = pv != null ? pv.toString() : "";
                                eap.setValorUsuario(s);
                                if (eapToPersist == null) {
                                    eapToPersist = new ArrayList(); // se inicializa pero jamas se usa en el metodo
                                }
                                entidadValorPadre = eap.getValorEntidadPadre();
                                entidadAtributoPadreService.addParentEntityAttribute(eap);
                            } else {
                                entidadValorPadre = entidadAtributoPadreService.findParentValueByEntityValueAndEntityId(va.getEntidadAtributo(), e.getXxcntIdEntidadPk());
                            }
                            va.setXxcntIdAtributoFk(currentAtt.getXxcntIdAtributoPk());
                            va.setEntidadValorPadre(entidadValorPadre);
                            this.valorAtributoService.addValorAtributo(va);
                        } else if (!col.equals(vaInDBAuxS)) {
                            ValorAtributoRespaldo var = getValorAtributoRespaldo(valnDB);
                            valorAtributoRespaldoService.create(var);
                            valnDB.setValorAtributo(col);
                            this.valorAtributoService.update(valnDB);
                        }
                    }
                }
            }
            log.info("Procesamiento de archivo finalizado");

        } else {
            log.info("No se recibió archivo");
        }
    } catch (IOException e) {
        log.error("Error al procesar los atributos", e);
        throw new IOException("Error al procesar los atributos" + e.getMessage(),e);
    }
    log.info("Fin del método processAtributos");
    return "exito";
}

And this is how I configure Postman:

Method: POST
URL: [ENDPOINT_URL]
Body: form-data
Key: listDTO
Value: [JSON_OF_DTO_LIST]
Key: file
Value: [FILE]
I noticed that if I change the @RequestPart annotation to @RequestBody for the list of DTOs and send the data as JSON in Postman, it works correctly for the list, but the issue persists with the file.

Can anyone help me understand why I am receiving this error and how I can fix it?

Thanks in advance!


I noticed that if I change the @RequestPart annotation to @RequestBody for the list of DTOs and send the data as JSON in Postman, it works correctly for the list, but the issue persists with the file.

Can anyone help me understand why I am receiving this error and how I can fix it?
java spring spring-boot postman
1个回答
0
投票

如果您想在请求中返回文件,您应该将请求映射更新为以下内容:

@PostMapping(value = "/upload", produces = {"application/octet-stream"})

如果需要,您还可以使用 org.springframework.util.MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE 而不是其中的字符串值。

© www.soinside.com 2019 - 2024. All rights reserved.