Submit a Post request with a file and JSON information included

I'm encountering an issue while trying to pass files with a JSON object. It seems like there might be an error in the controller where the 'consumes' and 'produces' declarations are possibly incorrect. I need assistance on how to attach one or more files to a document. The errors I encounter are usually of various types.

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'

  • Response Body
{
  "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' });
  }

Call to Service

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

Answer №1

A while back, I encountered a similar issue which I resolved by following these steps:

const jsonData = JSON.stringify(data);

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

const dataFile = new File([ dataBlob ], 'DataFile.json');

const formData = new FormData();
formData.append('data', dataFile, 'DataFile.json');

You can find my original solution here:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Where should global['window'] be defined for Angular 9 SSR with the use of domino?

Since the upgrade to Angular 9, an error message ReferenceError: window is not defined pops up when executing yarn serve:ssr. Our Angular apps utilize a trick involving Domino to simulate window for SSR (as shown in https://github.com/Angular-RU/angular-u ...

Enabling CORS in a Servlet implementation

In my servlet's doPost method, I implemented a header method to enable CORS. Despite this, I am encountering a CORS error in my reactjs application when trying to fetch the API. The error message from ReactJS states: "has been blocked by CORS policy: ...

Why are the icon pictures not displaying in Angular's mat-icon-button?

Recently, I stumbled upon a snippet of code in an Angular project that caught my eye. Naturally, I decided to incorporate it into my own program: <div style="text-align:center"> <a mat-icon-button class="btn-google-plus" href="http://google.com ...

Converting Apache POI Word documents to clean HTML stripping out styles and superfluous tags

I am currently working on converting Word documents to clean HTML. I have been using Apache POI, but it seems to create messy output similar to MS Word's own HTML saving method. What I really need is a solution like the one offered by . For instance, ...

What could be the reason for typescript not issuing a warning regarding the return type in this specific function?

For instance, there is an onClick event handler attached to a <div> element. The handler function is supposed to return a value of type React.MouseEventHandler<HTMLDivElement> | undefined. Surprisingly, even if I return a boolean value of fal ...

Guide to integrating Gandi.Net API with Node.js in server.js

I'm a beginner in Node.Js and I'm currently working on creating a Mean Stack application. One of the things I need to do is call a 3rd party API, specifically Gandi.Net, from my Node.js code. My Node.Js and Express Application are being used to ...

The Angular component seems to be failing to refresh the user interface despite changes in value

Recently, I created a simple component that utilizes a variable to manage its state. The goal is to have the UI display different content based on changes in this variable. To test this functionality, I implemented the component and used a wait function to ...

A comprehensive guide on utilizing the ngFor directive for looping through objects

After trying to iterate over this dataset within my HTML, I attempted a nested ngfor, but unfortunately encountered an error. My attempt involved iterating the object twice with a nested ngfor, resulting in the following error: HabitRecordsComponent.ht ...

Tips for resolving the issue of "The types 'GameState' and 'string' do not intersect, so this condition will always yield 'false'."

I need to display different components based on the value of gameStatus: import React from "react"; import { useAppSelector } from "./hooks/redux"; import EndScreen from "./pages/EndScreen"; import QuestionsPage from "./p ...

Suggestions for deleting browser cache programmatically by utilizing JS or HTML

Having trouble clearing the Chrome browser cache using Add-ons. Working on a site development project using JSP with Java, it's crucial for security reasons to clear the cache. Tried multiple methods but none have been successful. Any suggestions? Ple ...

Learn the steps to designing a responsive class using Angular2's ngClass feature

Imagine a scenario where the object models in my cloud Array include a weight key: return [ { term: '1994', weight: 0 }, { term: '2017', weight: 0 }, { term: '89th', ...

Selenium's final outcome: pass or fail based on condition

Reflect upon: if(driver.findElement(By.xpath("//*[@id='myClass']/tr[1]")) != null){ // Test Passed } else{ // Test Failed } What code can be added to show pass or fail status for Selenium tests? Using System.out.println("f ...

The Angular 2 rollup AoT compilation results in a larger build size compared to the standard JiT build

I'm facing an issue with reducing the weight of my app during the building process. I am using Angular 2 seed as a starting point. https://github.com/mgechev/angular-seed When I run: npm run build.prod my app.js file size is 1.5MB. However, when I ...

Execute multiple observables concurrently, without any delay, for every element within a given list

I've been attempting to utilize mergeMap in order to solve this particular issue, but I'm uncertain if my approach is correct. Within my code, there exists a method named getNumbers(), which makes an HTTP request and returns a list of numbers (O ...

Angular4 application Docker container: The executable file specified with the "-p" command was not found within the $PATH

Looking to set up a Docker container for my Angular 4 application. I have successfully built the image : docker build -t front:Angular4 -f src/main/docker/Dockerfile . Attempted to create and run the container instance of my image with: docker run --na ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

Struggling to understand how to properly 'map' my data from the response in Next.js 13 using Typescript

Just a few days into my journey with next.js, and I'm already facing a challenge in figuring out how to fetch data from an API. In regular React, I would typically use useState and useEffect for managing state and fetching data. But when it comes to n ...

Obtaining a TemplateRef from a directive: The process explained

I am currently working on developing a structural directive that can insert a TemplateRef, although the actual TemplateRef is defined in a separate location. Situation There are times when I need to add custom content within an existing element, but due ...

Simple method for detecting collisions between objects by projecting their shapes onto one

For the past few days, I've been delving into the world of Vectors and doing some research, but I'm still struggling to fully grasp the mathematics involved. In my code, I have two AABB's. When they collide, I want the method to return a Ve ...

Passing Toastr to child component in Angular 4 was successfully implemented

I am working with a parent component that utilizes ng2-toastr version 4.1.2. Parent Component: import { Component, ViewContainerRef } from '@angular/core'; import { AfterViewInit, ViewChild } from '@angular/core'; import { Rou ...