1 回答

TA貢獻1802條經驗 獲得超6個贊
我相信你的目標如下。
您想要使用 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>
修改要點:
從您的錯誤消息來看,我認為文件可能無法正確上傳。
在此修改后的腳本中,
FormData()
未使用。
在“mediaItems.batchCreate”方法中,多個文件上傳后,它們的文件可以用于一次API調用。
請求體的內容類型
https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate
為application/json
。所以在這種情況下,請使用JSON.stringify
請求正文。
當以上幾點反映到您的腳本中時,它會變成如下所示。在此修改中,作為示例情況,添加了 HTML 標簽。
修改后的腳本:
HTML 端:
<input?type="file"?id="files"?name="file"?multiple> <input?type="button"?onclick="run()"?value="ok">
JavaScript 方面:
請將您的訪問令牌設置為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));
}
筆記:
在此修改后的腳本中,假設您的訪問令牌可用于使用 Google Photo API 將圖像文件上傳到 Google Photo。請小心這一點。
在此修改后的腳本中,作為示例情況,添加了 HTML 標簽。在我的環境中,我可以確認上述修改后的腳本有效。但我認為上面的 HTML 標簽可能與您的實際情況有所不同。所以請根據您的實際情況修改上面的腳本。
添加回答
舉報