Search code examples
javascriptangularjsfile-uploadxmlhttprequestgoogle-cloud-storage

error: Bad content type. Please use multipart


I'm totally new to file uploads....I'm using angular-file-upload which creates an XHR outside of angularjs to upload files to google cloud storage. When I try to upload I keep getting the error below. How can I resolve this?

400 Bad content type. Please use multipart.

Here's my controller setup:

var uploader = $scope.uploader = new FileUploader({
      url: 'https://www.googleapis.com/upload/storage/v1/b/bucketsbuckets/o?uploadType=multipart',
      headers : {
            'Authorization': 'Bearer ya29.lgHmbYk-5FgxRElKafV4qdyWsdMjBFoO97S75p4vB0G0d6fryD5LASpf3JUY8Av9Yzhp9cQP8IQqhA', 
            'Content-Type': 'multipart/form-data'
      },
      autoUpload:true
  });

Solution

  • The problem is that the endpoint you're using is for multipart uploads, but not FORM-based multipart uploads. If you set your Content-Type to "multipart/related" instead of "multipart/form-data", you should be able to proceed.

    A multipart upload to that endpoint, "www.googleapis.com/upload/storage/etc?uploadType=multipart", expects a multipart message with exactly two parts, the first part being the metadata of the object, in JSON, and the second part being the data.

    More on these requirements are here: https://cloud.google.com/storage/docs/json_api/v1/how-tos/upload

    If, however, you'd like to do an upload in the style of a form submission, that's also possible, but the rules are different. In this case, you'll submit a POST to "storage.googleapis.com/BUCKET/OBJECT" with a variety of appropriate form parameters: https://cloud.google.com/storage/docs/reference-methods#postobject

    Now, this all assumes you're trying to do an upload as a multipart request for some reason. That might be necessary if you need to set some specific metadata properties on the object, but if not, you may be making things harder for yourself. A simple PUT to "storage.googleapis.com/BUCKET/OBJECT" will work just fine (although I'm not familiar with angular-file-upload and don't know whether it supports non-form-style uploads).