mgonto / restangular

AngularJS service to handle Rest API Restful Resources properly and easily
MIT License
7.88k stars 843 forks source link

Sending multipart/mixed works on $http but not Restangular #1169

Open xevenheaven opened 9 years ago

xevenheaven commented 9 years ago

I'm trying to upload a file in two parts. Here's the FormData I've created:

var formData = new FormData();
var fileMetaBlob = new Blob([angular.toJson(fileMeta)], { // fileMeta is a JSON obj
    type: 'application/json'
});
var fileStream = new FileReader().readAsArrayBuffer(file); // file is a File object
var fileBlob = new Blob([fileStream]);

formData.append('fileInfo', fileMetaBlob); // First part: application/json
formData.append('fileData', fileBlob); // Second part: application/octet-stream

I've tried uploading using $http and server returns status 200.

$http
    .post(url, formData, {
        transformRequest: angular.identity,
        headers: {'Content-Type': 'multipart/mixed'}
    })
    .success(function (data, status, headers, config) {
        // Handle successful upload
    })
    .error(function (error) {
        // Handle error in upload
    });

However, when I tried with Restangular, server returns status 400.

Restangular
    .one(url)
    .withHttpConfig({transformRequest: angular.identity})
    .customPOST(formData, undefined, undefined, {
        'Content-Type': 'multipart/mixed'
    }).then(function (response) {
        // Handle successful upload
    }, function (error) {
        // Handle error in upload
    });

Can anybody shed light on this? Any help is greatly appreciated! Thanks! :blush:

nass600 commented 8 years ago

@xevenheaven Did you find a solution?

xevenheaven commented 8 years ago

@nass600, I couldn't post with multipart/mixed so I went by modifying the formData and sending Content-Type: undefined in the end:

// Create FormData to send in the request
var formData = new FormData();

// Create Blob for the first part (application/json)
var fileMetaBlob = new Blob(
    [angular.toJson(fileMeta)],
    {type: 'application/json'}
);

// Create Blob for the second part (application/octet-stream)
var fileBlob = new Blob(
    [fileStream],
    {type: 'application/octet-stream'}
);

// Append both parts
formData.append('fileInfo', fileMetaBlob);
formData.append('fileData', fileBlob, fileMeta.fileName);

// Restangular Custom POST
return Restangular
    .one(url)
    .withHttpConfig({
        transformRequest: angular.identity,
        timeout: 0 // Avoid global setting's timeout on upload
    })
    .customPOST(formData, undefined, undefined, {
        'Content-Type': undefined
    });

Not sure if it helps, but sure do hope it does!

gowthamgts commented 6 years ago

This helped me. Thanks @xevenheaven