You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apex上传文件至Google Drive指定文件夹失败求助

Fix: File Uploads to Google Drive Root Instead of Target Folder

Let's break down exactly why your Apex code is dropping files in the Drive root instead of your specified folder, and how to fix it quickly.

The Core Issue: Wrong Content-Type for Metadata Part

Your multipart request has a critical formatting mistake: you're setting the Content-Type of the metadata JSON part to application/pdf instead of application/json. Google Drive can't parse the parents parameter when it's wrapped in a part marked as PDF content, so it ignores the folder ID entirely and defaults to the root directory.

Look at the problematic line in your code:

String body=delimiter+'Content-Type: application/pdf\r\n\r\n'+'{ "title" : "'+ filename+'",'+ ' "mimeType" : "' + att.ContentType+ '",'+ '"parents":[{"id":"'+ FolderId +'"}] }' + ...

The Fix: Correct the Metadata Content-Type

Change the Content-Type of the first multipart section to application/json so Drive recognizes it as file metadata. Here's the corrected code snippet:

String boundary = '----------9889464542212'; 
String delimiter = '\r\n--' + boundary +'\r\n'; 
String close_delim = '\r\n--' + boundary + '--'; 
String bodyEncoded = EncodingUtil.base64Encode(att.Body); 
String FolderId= '1U0vuP53dpIAM_WlmbJfvwvMCK0XZREOo'; 

// Fixed: Set metadata part to application/json
String body=delimiter+'Content-Type: application/json\r\n\r\n'+'{ "title" : "'+ filename+'",'+ ' "mimeType" : "' + att.ContentType+ '",'+ '"parents":[{"id":"'+ FolderId +'"}] }' + 
delimiter+'Content-Type: ' + att.ContentType +'\nContent-Transfer-Encoding: base64\r\n'+'\r\n'+ '\r\n'+bodyEncoded+close_delim; 

Why This Works

Multipart requests rely on correct Content-Type headers for each section to tell the server how to process the data. When you mark the metadata JSON as application/json, Google Drive will parse that section, recognize the parents array, and place the file in your target folder instead of falling back to the root.

Verify the Request

After making this change, your request content should look like this (note the first part's Content-Type):

------------9889464542212 
Content-Type: application/json 
{ "title" : "tester 83_Resume", "mimeType" : "application/pdf","parents":[{"id":"1U0vuP53dpIAM_WlmbJfvwvMCK0XZREOo"}] } 
------------9889464542212 
Content-Type: application/pdf 
Content-Transfer-Encoding: base64 

When you run this corrected code, the returned parents field in the response should match your target folder ID instead of the root folder ID.

内容的提问来源于stack exchange,提问作者vardhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:32:48