ZendeskファイルアップロードAPIエンドポイントにbase64でエンコードされたPDFファイルを投稿しようとしていますが、APIから返されたファイルURLはファイルが破損していることを示しています。Base64でエンコードされたPDFファイルをAJAXで投稿する
まず、別のAPI呼び出しからPDFをbase64でエンコードされた文字列として受け取ります。それをbase64String
としましょう。
window.open("data:application/pdf;base64," + base64String)
私はブラウザでPDFを見ることができます。
ここでは、APIを使用してファイルをアップロードするためのドキュメントhereに従っています。この例に示すように、cURL呼び出しを正常に完了できます。ただし、jQuery AJAX呼び出しによってPDFファイルが破損します。
client.request({
url: '/api/v2/uploads.json?filename=test.pdf',
type: 'POST',
data: atob(base64String),
contentType: 'application/binary'
}).then(function(data) {
window.open(data.upload.attachment.content_url); // corrupt file
}, function(response) {
console.log("Failed to upload file to Zendesk.");
console.log(response);
});
私が言ったように、これは成功しますが、私はcontent_url
を訪問したときにPDFが表示されません。 POST
リクエストでファイルが壊れていることは間違いありません。
他のものの中で運がなく、私はbase64の文字列(atob()
でデコードせずに)としてファイルをアップロードしようとしました。
UPDATE
私はまだブロブにbase64文字列を変換した後、PDFを閲覧することはできませんよ。
var blob = base64ToBlob(base64String);
console.log(blob); // Blob {size:39574, type: "application/pdf"}
client.request({
url: '/api/v2/uploads.json?filename=test.pdf',
type: 'POST',
data: blob,
processData: false,
contentType: 'application/pdf'
}).then(function(data) {
window.open(data.upload.attachment.content_url); // corrupt file
}, function(response) {
console.log("Failed to upload file to Zendesk.");
console.log(response);
});
function base64ToBlob(byteString) {
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ab], {type: 'application/pdf'});
return blob;
};
なぜ 'contentType'を' 'application/binary''に設定していますか? – guest271314
[cURLの例](https://developer.zendesk.com/rest_api/docs/core/attachments#upload-files)を見ると、そのヘッダがあります。 – rosendin
サーバーのPOST要求を別の言語で処理しようとしましたが、クライアントの問題であることを確認しましたか? – user2867288