java - Post请求中传递文件和Json数据

标签 java angular typescript rest jhipster

我需要传递带有 json 对象的文件,但收到相同的错误。 我认为 Controller 中的消费和生产可能没有正确定义。 我需要知道如何将一个或多个文件附加到文档中。 错误几乎总是不同类型。

控制台

{
  "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))
  }

文档.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
  ) { }
}

最佳答案

我之前也遇到过同样的问题, 直到我这样做:

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');

我原来的答案:

https://stackoverflow.com/a/51017150/5485675

关于java - Post请求中传递文件和Json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60719103/

相关文章:

angular - 将表单字段动态添加到 Angular 8 中的 react 表单

jquery - 在 Angular 世界之外发生更改时如何更新 Angular 2 Reactive 表单字段

java - PHP 的 oAuth 客户端模块

java - 使用 Apache POI 获取大型 Excel 文件的 Excel 工作表名称

Angular5 : where are "converters" ?(即像 JSF)

javascript - 使用 String.toLowerCase 进行 Typescript 字符串比较

typescript - PrimeNG Angular 8 p-dropdown selectedItem 模板未渲染

javascript - 在 Typescript 中声明变量时使用类型有什么意义?

java - 从包含部门列表的员工对象制作部门到员工列表的映射

java - 在运行时将表名传递给实体的 @Table 注解 Hibernate