I’m stuck trying to upload an image to Google Drive using the v2 API in my ASP.NET MVC project. The upload works fine in Postman, but my code keeps getting a 400 Bad Request error.
Here’s a simplified version of my code:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://www.googleapis.com");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
client.DefaultRequestHeaders.Add("Accept", "application/json");
using (var content = new MultipartFormDataContent())
{
var imageBytes = File.ReadAllBytes(imagePath);
var imageContent = new ByteArrayContent(imageBytes);
imageContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("file")
{
FileName = "picture.jpg"
};
content.Add(imageContent);
var uploadEndpoint = "/upload/drive/v2/files/" + driveFileId;
var response = await client.PutAsync(uploadEndpoint, content);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine($"Error: {response.StatusCode}");
}
}
}
I’ve double-checked the access token and file ID. Any ideas why this might be failing?
hey finn, i had similar issue. try adding content type header to ur imageContent:
imageContent.Headers.ContentType = new MediaTypeHeaderValue(“image/jpeg”);
also, double check ur access token scope. it should include https://www.googleapis.com/auth/drive.file
hope this helps!
I encountered a similar issue when working with the Google Drive API. One crucial detail often overlooked is the ‘uploadType’ query parameter. Try modifying your upload endpoint to include this:
var uploadEndpoint = $“/upload/drive/v2/files/{driveFileId}?uploadType=media”;
This parameter tells the API you’re doing a media upload. Also, ensure your ‘Authorization’ header is correct - it should be 'Bearer ’ followed by a space and then your token. Lastly, verify that your access token hasn’t expired. These steps resolved the 400 error in my case.
I’ve dealt with this exact problem before, and it can be frustrating. One thing that’s not immediately obvious is that the Google Drive API v2 is quite outdated now. I’d strongly recommend switching to v3 if possible, as it’s more robust and better documented.
In my experience, the issue often lies in how the request is constructed. Try simplifying your approach by using Google’s official .NET client library instead of crafting the HTTP request manually. It handles a lot of the low-level details for you, including authentication and request formatting.
Here’s a rough outline of how I got it working:
- Install the Google.Apis.Drive.v3 NuGet package
- Set up authentication using a service account or OAuth 2.0
- Use the FilesResource.Update method for existing files
This approach eliminated the 400 errors for me and made the whole process much smoother. Plus, it’s easier to maintain in the long run.