1 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個(gè)贊
我相信你的目標(biāo)如下。
您想要使用 axios 和 Javascript 使用 Google Photo API 將圖像文件上傳到 Google Photo。
images
是來自.?const promises = Array.from(images).map(image => {
_document.getElementById("###").files
<input type="file" id="files" name="file" multiple>
修改要點(diǎn):
從您的錯(cuò)誤消息來看,我認(rèn)為文件可能無法正確上傳。
在此修改后的腳本中,
FormData()
未使用。
在“mediaItems.batchCreate”方法中,多個(gè)文件上傳后,它們的文件可以用于一次API調(diào)用。
請(qǐng)求體的內(nèi)容類型
https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate
為application/json
。所以在這種情況下,請(qǐng)使用JSON.stringify
請(qǐng)求正文。
當(dāng)以上幾點(diǎn)反映到您的腳本中時(shí),它會(huì)變成如下所示。在此修改中,作為示例情況,添加了 HTML 標(biāo)簽。
修改后的腳本:
HTML 端:
<input?type="file"?id="files"?name="file"?multiple> <input?type="button"?onclick="run()"?value="ok">
JavaScript 方面:
請(qǐng)將您的訪問令牌設(shè)置為token
。
function uploadImages(images, token) {
? const promises = Array.from(images).map(image => {
? ? return new Promise(r => {
? ? ? axios.post("https://photoslibrary.googleapis.com/v1/uploads", image, {
? ? ? ? headers: {
? ? ? ? ? 'Content-Type': "application/octet-stream",
? ? ? ? ? 'X-Goog-Upload-File-Name': image.name,
? ? ? ? ? 'X-Goog-Upload-Protocol': "raw",
? ? ? ? ? 'Authorization': `Bearer ${token}`,
? ? ? ? }
? ? ? }).then((response) => {
? ? ? ? r({description: "item-description", simpleMediaItem: {fileName: image.name, uploadToken: response.data}});
? ? ? });
? ? });
? });
? return Promise.all(promises).then(e => {
? ? return new Promise((resolve, reject) => {
? ? ? axios.post('https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate',
? ? ? ? JSON.stringify({newMediaItems: e}),
? ? ? ? {headers: {'Content-type': 'application/json', 'Authorization': `Bearer ${token}`},
? ? ? })
? ? ? .then(resolve)
? ? ? .catch(reject);
? ? });
? });
}
// This function is run.
function run() {
? const token = "###";? // Please set your access token.
? const files = document.getElementById("files").files;
? uploadImages(files, token)
? .then(e => console.log(e))
? .catch(err => console.log(err));
}
筆記:
在此修改后的腳本中,假設(shè)您的訪問令牌可用于使用 Google Photo API 將圖像文件上傳到 Google Photo。請(qǐng)小心這一點(diǎn)。
在此修改后的腳本中,作為示例情況,添加了 HTML 標(biāo)簽。在我的環(huán)境中,我可以確認(rèn)上述修改后的腳本有效。但我認(rèn)為上面的 HTML 標(biāo)簽可能與您的實(shí)際情況有所不同。所以請(qǐng)根據(jù)您的實(shí)際情況修改上面的腳本。
添加回答
舉報(bào)