Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

javascript - How to use AngularJS $http to send multipart/form-data

I am developing a graphical interface that uses different services rest (written in java). I have to call up 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 request from my Angularjs service file I get: error 400 (bad request) if the service has a Content-Type = multipart / form-data

While I get a 415 (unsupported media type) error if the service has a Content-Type = "application / x-www-form-urlencoded; charset = utf-8" or "application / json; charset = utf-8" or "application / form-data ".

I am developing the front-end in javascript and html5, I did not find anything in the web that can help me as the FormDataMultiPart object does not exist in javascript.

I tried to format the data to send in many ways but it always returns 400 or 415.

How should I format the data to send to the rest call?

And how should the Content-Type be in the headers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

How to use AngularJS $http to send FormData

The FormData interface provides a way 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 a form would use if the encoding type were 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 content type header to undefined. Normally the $http service sets the content type to application/json. When the content type is undefined, the XHR API will automatically set the content type to multipart/form-data with the proper multi-part boundary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...