Rest - Http Post Multipart with JSON

REST - HTTP Post Multipart with JSON

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--

sending file and json in POST multipart/form-data request with axios

To set a content-type you need to pass a file-like object. You can create one using a Blob.

const obj = {
hello: "world"
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
type: 'application/json'
});
const data = new FormData();
data.append("document", blob);
axios({
method: 'post',
url: '/sample',
data: data,
})

Rest Assured - Send POST Request (Content-Type : multipart/form-data) with Static JSON Payload and Files to be uploaded

You need to use multiPart() methods for uploading files, not body() method. For example:

File json = new File("src/test/resources/test_new.json");
File file = new File("src/test/resources/debug.log");

given().log().all()
.multiPart("files", file)
.multiPart("body", json, "application/json")
.post("your_url");

How to send the Multipart file and json data to spring boot

You cat use @RequestParam and Converter for JSON objects

simple example :

@SpringBootApplication
public class ExampleApplication {

public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}

@Data
public static class User {
private String name;
private String lastName;
}

@Component
public static class StringToUserConverter implements Converter<String, User> {

@Autowired
private ObjectMapper objectMapper;

@Override
@SneakyThrows
public User convert(String source) {
return objectMapper.readValue(source, User.class);
}
}

@RestController
public static class MyController {

@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file,
@RequestParam("user") User user) {
return user + "\n" + file.getOriginalFilename() + "\n" + file.getSize();
}

}

}

and postman:
Sample Image

UPDATE
apache httpclient 4.5.6 example:

pom.xml dependency:

    <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.6</version>
</dependency>

<!--dependency for IO utils-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>

service will be run after application fully startup, change File path for your file

@Service
public class ApacheHttpClientExample implements ApplicationRunner {

private final ObjectMapper mapper;

public ApacheHttpClientExample(ObjectMapper mapper) {
this.mapper = mapper;
}

@Override
public void run(ApplicationArguments args) {
try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
File file = new File("yourFilePath/src/main/resources/foo.json");
HttpPost httpPost = new HttpPost("http://localhost:8080/upload");

ExampleApplication.User user = new ExampleApplication.User();
user.setName("foo");
user.setLastName("bar");
StringBody userBody = new StringBody(mapper.writeValueAsString(user), MULTIPART_FORM_DATA);
FileBody fileBody = new FileBody(file, DEFAULT_BINARY);

MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.addPart("user", userBody);
entityBuilder.addPart("file", fileBody);
HttpEntity entity = entityBuilder.build();
httpPost.setEntity(entity);

HttpResponse response = client.execute(httpPost);
HttpEntity responseEntity = response.getEntity();

// print response
System.out.println(IOUtils.toString(responseEntity.getContent(), UTF_8));
} catch (Exception e) {
e.printStackTrace();
}
}

}

console output will look like below:

ExampleApplication.User(name=foo, lastName=bar)
foo.json
41

Posting a File and Associated Data to a RESTful WebService preferably as JSON

I asked a similar question here:

How do I upload a file with metadata using a REST web service?

You basically have three choices:

  1. Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
  2. Send the file first in a multipart/form-data POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata.
  3. Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.

How to upload a file and JSON data in Postman?

In postman, set method type to POST.

Then select
Body -> form-data -> Enter your parameter name (file according to your code)

On the right side of the Key field, while hovering your mouse over it, there is a dropdown menu to select between Text/File. Select File, then a "Select Files" button will appear in the Value field.

For rest of "text" based parameters, you can post it like normally you do with postman. Just enter parameter name and select "text" from that right side dropdown menu and enter any value for it, hit send button. Your controller method should get called.



Related Topics



Leave a reply



Submit