parondeau
parondeau

Reputation: 123

Uploading image to Parse using Javascript(CoffeeScript) and REST API

I'm trying to upload images to parse and later attach them to models, however whenever I upload one it returns as a successful upload but the url contains a broken image link.

for instance:

http://files.parse.com/aac0413c-eada-4602-9451-2ee5da7d1241/22eaa50b-1e61-4744-abf9-a57ba9f4123f-test.jpg

Here's the upload code:

getImg: ->
CameraHelper.fileUpload (file) =>
    @file = file
    forge.file.URL file, (url) =>
        @fileURL = url
        @$("#uploadImg").addClass("fadeIn").css("background-image", "url(#{url})")
        @$("#removeImg").css("display", "inline")
    , (content) ->
        error "Error finding Image"
, ->
    debug "Upload Cancelled"


    serverUrl = 'https://api.parse.com/1/files/test.jpg'
    parseFile = _.extend @file,
        type: "image/jpeg"
        name: "share.jpg"

    $.ajax
        type: "POST",
        beforeSend: (request)->
            request.setRequestHeader "X-Parse-Application-Id", 'MY-APP-ID'
            request.setRequestHeader "X-Parse-REST-API-Key", 'MY-REST-API-ID'
            request.setRequestHeader "Content-Type", "image/jpeg"
        url: serverUrl
        data: parseFile
        processData: false
        contentType: false
        success: (data) ->
            alert "File available at: " + data.url
        error: (data) ->
            obj = jQuery.parseJSON(data)
            alert obj

CameraHelper =
fileUpload: (success, err) ->
    if APP
        forge.file.getImage
            saveLocation: "file"
            source: "camera"
            height: "620px"
            width: "620px"
        , (file) ->
            debug "Successfully uploaded img"
            success?(file)
        , (content) ->
            error "Error in uploading img", content
            err?()
    else
        debug "Sorry that feature is not currently available on the mobile web."

CameraHelper NOTE: I'm using triggerIO, also referenced: https://www.parse.com/questions/uploading-files-to-parse-using-javascript-and-the-rest-api to no avail

parseFile is the image I'm trying to upload

Upvotes: 1

Views: 1151

Answers (1)

James Brady
James Brady

Reputation: 27492

I'm not sure exactly what Parse are expecting in the POST body, but I think they want the entire body to be the image data, with no multi-part encoding.

That means you need to do two things:

Firstly, when uploading files, you should use the files parameter, rather than data. See https://trigger.io/docs/current/api/modules/request.html#forgerequestajaxoptions. This is true whenever you're uploading files, not just with Parse.

Secondly, as I think Parse don't want an encoded POST body, use the fileUploadMethod: "raw" parameter to just dump the image data directly into the request.

Upvotes: 1

Related Questions