How to use AngularJS $ http to send multipart / form-data
I am developing a GUI that uses different rest services (written in java). I need to call a service like this:
@PUT
@Path("nomeServizio")
public Response nomeServizio(final FormDataMultiPart multiPart) {
......}
Call service:
service: function (data) {
return $http({
url: PATH_REST_SERVICES + '/nomeServizio',
headers: {"Content-Type": "multipart/form-data"},
data: data,
method: "PUT"
});
}
When I query my Angularjs service file I get: error 400 (failed request) if service has Content-Type = multipart / form-data p>
So far, I am getting error 415 (unsupported media type) if the service has Content-Type = "application / x-www-form-urlencoded; charset = utf-8" or "application / json; charset = utf-8" or " application / form-data ".
I am developing front-end in javascript and html5, I have not found anything on the internet that can help me as FormDataMultiPart object does not exist in javascript.
I tried to format the data to send in different ways, but it always returns 400 or 415.
How do I format the data to send to the remaining call?
And how should Content-Type be in headers?
source to share
How to use AngularJS $ http to send FormData h1>
The FormData interface provides the ability to easily construct a set of key / value pairs representing form fields and their values, which can then be easily sent using the XHR Send method . It uses the same format that the form would use if the encoding type was set to multipart/form-data
.
var formData = new FormData();
formData.append('type', type);
formData.append('description', description);
formData.append('photo', photo);
return $http({
url: PATH_REST_SERVICES + '/nomeServizio',
headers: {"Content-Type": undefined },
data: formData,
method: "PUT"
});
It is important to set the title of the content type undefined
. Usually $ http service sets the content type application/json
. When the content is type undefined
, the XHR API will automatically set the content type multipart/form-data
using the correct multipart border .
source to share
in java code you need to write code like this:
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
for more information you can refer to below example and link: -
https://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/
source to share