restangular icon indicating copy to clipboard operation
restangular copied to clipboard

Sending multipart/mixed works on $http but not Restangular

Open xevenheaven opened this issue 9 years ago • 3 comments

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:

xevenheaven avatar Jun 09 '15 10:06 xevenheaven

@xevenheaven Did you find a solution?

nass600 avatar Nov 03 '15 11:11 nass600

@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!

xevenheaven avatar Nov 13 '15 08:11 xevenheaven

This helped me. Thanks @xevenheaven

gowthamgts avatar Aug 01 '17 12:08 gowthamgts