Файл пропуска и Json данные в почтовом запросе - PullRequest
0 голосов
/ 17 марта 2020

Мне нужны файлы с объектом json, но я получаю ту же ошибку. Я думаю, что это возможно, что в контроллере, потребляет и производит не правильно определены. Мне нужно знать, как прикрепить один или несколько файлов к документу. Ошибки почти всегда различного типа.

console

{
  "type" : "https://www.jhipster.tech/problem/problem-with-message",
  "title" : "Unsupported Media Type",
  "status" : 415,
  "detail" : "Content type '' not supported",
  "path" : "/api/documents",
  "message" : "error.http.415"
}

API

  • curl
curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/problem+json' --header 'Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOiJST0xFX0FETUlOLFJPTEVfVVNFUiIsImV4cCI6MTU4NTQ5ODc1NX0.4WT8jo-775CLWlCXe-gkyj0iARmP85w1OGoha-uc-yAVE2EFEPfsvTwE0LOn1Ypqh0-4Dh_FxiAmayIbbeyazw' {"type":"formData"} 'http://localhost:8080/api/documents'

  • Тело ответа
{
  "type": "https://www.jhipster.tech/problem/problem-with-message",
  "title": "Unsupported Media Type",
  "status": 415,
  "detail": "Content type 'multipart/form-data;boundary=----WebKitFormBoundaryJHbbuWBb4WMI3DPz;charset=UTF-8' not supported",
  "path": "/api/documents",
  "message": "error.http.415"
}

DocumentResource. java

@PostMapping(value = "/documents", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Document> createDocument(@RequestBody Document document,
            @ApiParam(value = "Content binary", required = true) @RequestPart(value = "file", required = true) MultipartFile file)
            throws URISyntaxException, IllegalStateException, IOException {
        log.debug("REST request to save Document : {}", document);
        if (document.getId() != null) {
            throw new BadRequestAlertException("A new document cannot already have an ID", ENTITY_NAME, "idexists");
        }
        if (!file.isEmpty()) {
            String originalName = file.getOriginalFilename();
            String filePath = destinationPath + originalName;
            File destination = new File(filePath);

            file.transferTo(destination);
        } else {
                throw new BadRequestAlertException("The file is null or empty", ENTITY_NAME, "isnotexists");
        }

        Document result = documentRepository.save(document);
        return ResponseEntity
                .created(new URI("/api/documents/" + result.getId())).headers(HeaderUtil
                        .createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
                .body(result);
    }

document.service.ts


createWithFiles(document: IDocument, file: File): Observable<EntityResponseType> {
    const documentMultipartFormParam = 'document';
    const fileMultipartFormParam = 'file';
    const formData: FormData = new FormData();
    const documentAsJsonBlob: Blob = new Blob([JSON.stringify(document)]);

    formData.append(documentMultipartFormParam, documentAsJsonBlob);
    formData.append(fileMultipartFormParam, file.name);
    return this.http.post<IDocument>(this.resourceUrl, formData, { observe: 'response' });
  }

звонок в службу

document: IDocument;
file: File;

handleFileSelect($event) {
    this.file = $event.target.files[0];
    this.uploadFileToDeliverable();
  }

uploadFileToDeliverable() {
    this.subscribeToSaveResponse(this.documentService.createWithFiles(this.document, this.file))
  }

document.model.ts

export interface IDocument {
  id?: number;
  name?: string;
  extension?: string;
  path?: string;
  type?: string;
  uuid?: string;
  deliverables?: IDeliverable[];
}

export class Document implements IDocument {
  constructor(
    public id?: number,
    public name?: string,
    public extension?: string,
    public path?: string,
    public type?: string,
    public uuid?: string
  ) { }
}

1 Ответ

0 голосов
/ 17 марта 2020

У меня была такая же проблема некоторое время go, пока я не сделал это:

const st = JSON.stringify(json);

const blob = new Blob([st], { type: 'application/json' });

const file = new File([ blob ], 'FileName.json');

const formData = new FormData();
formData.append('file', file, 'FileName.json');

Мой оригинальный ответ:

{ ссылка }

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...