Upload Excel to Slack using files.upload API - fil

2019-07-27 01:26发布

问题:

I'm using Slack's files.upload API to upload an Excel doc retrieved from an AJAX response. I'm using jQuery's AJAX for the upload and the file is uploading correctly except that it's corrupted. When I open the file downloaded from Slack, it contains many "?"s and other characters indicative of bad encoding. Downloading the file and then uploading using Slack's tester tool, works correctly and does not result in corruption.

The most relevant portion is the ajaxConfig; this is the object passed to jQuery's ajax() method.

self.getClient().runReport({
    query: queryString,
    success: function(response){
        var formEnc = new FormData();
        formEnc.append('file', new Blob([response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}), 'filename.xls');
        self.getClient().slackFile({
            filename: 'MyReport.xls',
            channel: '%23my-channel',
            ajaxConfig: {
                method: 'post',
                data: formEnc,
                processData: false,
                contentType: false,
                mimeType: 'multipart/form-data',
                success: function(response){
                    resolve(response);
                },
                error: function(response){
                    reject(response);
                }
            }
        });
    },
    error: function(msg){
        reject(msg);
    }
});

I've tried different types for the Blob and the mimeType without success, though I don't think this is the problem because the POST request that I'm sending looks the same as the one generated by Slack's tester tool (which uploaded the file without corruption). I suspect that the problem must be in how I'm encoding the response I get from runReport (remember that I can download that file manually just fine).


Update I used FileSaver.js to download the response and the file is corrupted in the same way, so it's not related to the POST to Slack. It must be the encoding.

回答1:

It ended up being an an encoding problem caused by jquery. The upload works fine when using straight xhr.

var req = new XMLHttpRequest();
req.open(method, url);
req.responseType = 'arraybuffer';
req.onload = function(){
    success(req.response);
};
req.send();